Asp.net-Mvc
如何在 MVC 應用程序(IIS7.5)中將 HTTP 重定向到 HTTPS
我需要將我的 HTTP 站點重定向到 HTTPS,添加了以下規則,但是嘗試使用<http://www.example.com>時出現 403 錯誤,當我在瀏覽器中鍵入<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 中使用以下內容:
protected void Application_BeginRequest() { if (FormsAuthentication.RequireSSL && !Request.IsSecureConnection) { Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://")); } }
您可以在程式碼中執行此操作:
全球.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); } } }