您将的添加到ASP.net BasePage : System.Web.UI.Page
类中有哪些很酷的功能和方法?
例子
这是我用于身份验证的内容,我想听听您对此的意见:protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
// Authentication code omitted... Essentially same as below.
if (_RequiresAuthentication && !(IsAuthorized))
{
RespondForbidden("You do not have permissions to view this page.", UnauthorizedRedirect);
return;
}
}
// This function is overridden in each page subclass and fitted to each page's
// own authorization requirements.
// This also allows cascading authorization checks,
// e.g: User has permission to view page? No - base.IsAuthorized - Is user an admin?
protected virtual bool IsAuthorized
{
get { return true; }
}
我的BasePage类包含此类的一个实例:public class StatusCodeResponse {
public StatusCodeResponse(HttpContext context) {
this._context = context;
}
/// <summary>
/// Responds with a specified status code, and if specified - transfers to a page.
/// </summary>
private void RespondStatusCode(HttpContext context, System.Net.HttpStatusCode status, string message, string transfer)
{
if (string.IsNullOrEmpty(transfer))
{
throw new HttpException((int)status, message);
}
context.Response.StatusCode = (int)status;
context.Response.StatusDescription = message;
context.Server.Transfer(transfer);
}
public void RespondForbidden(string message, string transfer)
{
RespondStatusCode(this._context, System.Net.HttpStatusCode.Forbidden, message, transfer);
}
// And a few more like these...
}
附带说明,这可以通过使用HttpResponse
对象的扩展方法来完成。
我发现用于解析querystring int参数的另一种方法非常方便:public bool ParseId(string field, out int result)
{
return (int.TryParse(Request.QueryString[field], out result) && result > 0);
}
最佳答案
但最重要的是:请勿将您的基础设置为某些帮助程序类。不要添加
ParseId()
之类的东西,这太荒谬了。此外,根据第一篇文章:制作类似
IsAuthorized
和抽象之类的东西。这样,如果有人忘记了某种虚拟方法,就不会造成巨大的安全漏洞。