似乎ASP.NETMVC只是运行在ASP.NETWebForms之上。ASP.NET Mvc中的System.Web.Mvc.ViewPage继承自System.Web.UI.Page,后者包括OnRender和friends等页面生命周期方法。
我在网上看到了一些评论,大意是你应该抵制不惜一切代价重写这些方法的冲动!。当然,这意味着我发现自己抵制了这样做的冲动。
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);
}
}
有人可能会争论把它放在一个“观点”中的纯洁性,但这似乎是非常有利的。
重写这些方法有多危险/亵渎神明?什么时候说得通?