ASP.net"BasePage"类的想法

GeR*_*ReV 11 c# asp.net

在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; }
}
Run Code Online (Sandbox Code Playgroud)

我的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...

}
Run Code Online (Sandbox Code Playgroud)

作为旁注,这可以使用HttpResponse对象的扩展方法来完成.

另一种方法我觉得解析querystring int参数非常方便:

public bool ParseId(string field, out int result)
{
    return (int.TryParse(Request.QueryString[field], out result) && result > 0);
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*oom 5

  • 会话相关的东西,BasePage中映射到会话的一些复杂对象,并将其作为属性公开.
  • 做一些像填充碎屑垫物体的东西.

但最重要的是:不要让你的基页成为一些帮助类.不要添加类似的东西ParseId(),这太荒谬了.


另外,基于第一篇文章:制作像IsAuthorized 抽象的东西.这样,如果有人忘记了某种虚拟方法,就不会创建巨大的安全漏洞.