我需要重定向我的HTTP站点到HTTPS,已添加以下规则,但我得到403错误时尝试使用
http://www.example.com,它工作正常,当我在浏览器中键入
https://www.example.com。
<system.webServer> <rewrite> <rules> <rule name="HTTP to HTTPS redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" /> </rule> </rules> </rewrite> </system.webServer>
解决方法
你可以在代码中做到:
Global.asax.cs
protected void Application_BeginRequest(){ if (!Context.Request.IsSecureConnection) Response.Redirect(Context.Request.Url.ToString().Replace("http:","https:")); }
public class SSLFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext){ if (!filterContext.HttpContext.Request.IsSecureConnection){ var url = filterContext.HttpContext.Request.Url.ToString().Replace("http:","https:"); filterContext.Result = new RedirectResult(url); } } }