views:

63

answers:

1

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(EventArgs 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?

+3  A: 

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.

Dean Harding
Dean, thank you for clearing up my very silly mistake. I was adding MVC to an existing WebForms site and my mind was clearly in a request=page mode. Of course, you are right that a view (page) is only created at the request of the controller (much too late for what I was doing).
Justin