Asp.net-Mvc

如何在 MVC 應用程序(IIS7.5)中將 HTTP 重定向到 HTTPS

  • February 9, 2011

我需要將我的 HTTP 站點重定向到 HTTPS,添加了以下規則,但是嘗試使用<http://www.example.com>時出現 403 錯誤,當我在瀏覽器中鍵入<https://www.example.com>時它工作正常.

&lt;system.webServer&gt;
   &lt;rewrite&gt;
       &lt;rules&gt;
           &lt;rule name="HTTP to HTTPS redirect" stopProcessing="true"&gt;
               &lt;match url="(.*)" /&gt;
               &lt;conditions&gt;
                   &lt;add input="{HTTPS}" pattern="off" ignoreCase="true" /&gt;
               &lt;/conditions&gt;
               &lt;action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" /&gt;
           &lt;/rule&gt;
       &lt;/rules&gt;
   &lt;/rewrite&gt;
&lt;/system.webServer&gt;

我在 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);
       }
   }
}

引用自:https://stackoverflow.com/questions/4945883