[英]How to redirect from HTTP to HTTPS in the ASP.NET page lifecycle?
我有一个ASP.NET页面,其中添加了很多服务器控件。 当用户从HTTP访问页面时,我需要重定向请求以改为使用HTTPS。 控件是在Init
方法中动态加载的,而我正在Load
方法中进行重定向。 但这最终会创建一个循环,该循环加载控件,然后连续重定向。
我可以使用页面生命周期中的哪个事件来处理避免循环的重定向?
您应该使用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);
}
}
如果可用,则应使用IIS Rewrite来执行此操作。 规则是:
<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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.