【发布时间】:2011-10-14 11:27:31
【问题描述】:
我有一个 ASP.NET 页面,其中添加了很多服务器控件。当用户从 HTTP 访问页面时,我需要将请求重定向为使用 HTTPS。控件在Init 方法中动态加载,我正在Load 方法中进行重定向。但这最终会创建一个循环来加载控件,然后不断重定向。
我可以使用页面生命周期中的哪个事件来处理避免循环的重定向?
【问题讨论】:
标签: asp.net http iis-7 ssl https
我有一个 ASP.NET 页面,其中添加了很多服务器控件。当用户从 HTTP 访问页面时,我需要将请求重定向为使用 HTTPS。控件在Init 方法中动态加载,我正在Load 方法中进行重定向。但这最终会创建一个循环来加载控件,然后不断重定向。
我可以使用页面生命周期中的哪个事件来处理避免循环的重定向?
【问题讨论】:
标签: asp.net http iis-7 ssl https
您应该使用 Gloabal.asax 文件来执行此操作..试试这个 代码..
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if ( !Request.IsSecureConnection)
{
string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));
Response.Redirect(path);
}
}
【讨论】:
page lifecycle 中最早可以挂钩和重定向的点是 Page_PreInit 事件,因此我建议在此处执行您的方案检查和重定向。
【讨论】:
如果可用,您应该使用 IIS 重写来执行此操作。规则是:
<rule name="Redirect to HTTPS" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
</rule>
【讨论】:
如果您不想加载控件,您应该在页面初始化的开头重定向。我使用这样的东西来重定向(我只是发出我想要的代码):
protected void RedirectPage(string redirectUrl)
{
// Redirect the page, nothing should be shown in this case
if (redirectUrl.StartsWith("~"))
redirectUrl = ResolveClientUrl(redirectUrl);
Response.Write("<head id=\"pageheader\">");
Response.Write("</head>");
Response.Write("<body onload=\"window.location = '" + redirectUrl + "';\">");
Response.Write("</body>");
Response.End();
}
【讨论】: