C# 如何在C中配置站点以自动从HTTP重定向到HTTPS#
大约一个月前,我为我的网站设置了SSL。然而,我从未在网站上习惯过。 这些是我的问题:C# 如何在C中配置站点以自动从HTTP重定向到HTTPS#,c#,redirect,https,C#,Redirect,Https,大约一个月前,我为我的网站设置了SSL。然而,我从未在网站上习惯过。 这些是我的问题: 我手动输入https作为URL,因此自动重定向不起作用 SSL目前运行正常,但在那些链接(例如default.aspx、login.aspx)上不起作用 如果我在某些页面上手动输入https,它会自动从https重定向到http 代码: 我的问题是:如何配置一个站点在C#中自动从HTTP重定向到HTTPS?检查HTTP是否重定向到HTTPS: if(!Request.IsSecureConnection)
- 我手动输入https作为URL,因此自动重定向不起作用李>
- SSL目前运行正常,但在那些链接(例如default.aspx、login.aspx)上不起作用李>
- 如果我在某些页面上手动输入https,它会自动从https重定向到http李>
我的问题是:如何配置一个站点在C#中自动从HTTP重定向到HTTPS?检查
HTTP
是否重定向到HTTPS
:
if(!Request.IsSecureConnection)
{
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl);
}
if (!HttpContext.Current.Request.IsSecureConnection)
{
string redirectUrl = HttpContext.Current.Request.Url.ToString().Replace("http:", "https:");
HttpContext.Current.Response.Redirect(redirectUrl);
}
在
Application\u BeginRequest
方法的Global.asax
页面中,检查请求是否为http
。如果是,请将http
替换为https
:
if(!Request.IsSecureConnection)
{
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl);
}
if (!HttpContext.Current.Request.IsSecureConnection)
{
string redirectUrl = HttpContext.Current.Request.Url.ToString().Replace("http:", "https:");
HttpContext.Current.Response.Redirect(redirectUrl);
}
我个人更喜欢IIS的Url重写模块: 安装moudle后,可以在web.config中添加重定向:
<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="https" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
</rule>
</rules>
</rewrite>
</system.webServer>
页面加载中的代码当前配置为从HTTPS重定向到HTTP-如果这不是您想要的,请删除它!