开发者

When is it ok to meddle in the page lifecycle an ASP.NET MVC page?

It seems that ASP.NET MVC just runs on top of ASP.NET WebForms. System.Web.Mvc.ViewPage in ASP.NET MVC inherits from System.Web.UI.Page which includes page lifecycle methods like OnRender and friends.

I have seen a couple of comments around the web to the effect that you should resist the urge to override these methods AT ALL COSTS!. Of course, this means that I find myself resisting the urge to do just that.

Is there really that much wrong with something like the following?

public class SslPage : ViewPage
{
    protected override void OnPreInit(Ev开发者_如何学GoentArgs e)
    {
        // Make sure we are using SSL
        string url = HttpContext.Current.Request.Url.ToString();

        if(url.StartsWith("http:"))
        {
            HttpContext.Current.Response.Redirect("https" + url.Remove(0, 4),false);
        }

        // Back to our regularly scheduled programming...
        base.OnPreInit(e);
    }
}

One could debate the purity of putting that in a "View" but it seems plenty expedient.

How dangerous/blasphemous is it to override these methods? When might it make sense?


The problem with what you describe is that the view is only rendered once the controller decides which view to render. It may seem surprising at first, but by the time your OnPreInit method is called, all of the logic of the controller has already executed.

The correct place to put this, as @Ryan says, is in a filter or a base controller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜