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

问题描述:

我需要将我的HTTP站点重定向到HTTPS,添加了以下规则,但是当我尝试使用 http:/时,我收到403错误/www.example.com ,当我输入 https://www.example.com 时,它可以正常工作>在浏览器中。

I need to redirect my HTTP site to HTTPS, have added below rule but I am getting 403 Error when tried using http://www.example.com, it works fine when I type https://www.example.com in browser.

<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>


您可以在代码中执行此操作:

You can do it in code:

Global.asax.cs

Global.asax.cs

protected void Application_BeginRequest(){
    if (!Context.Request.IsSecureConnection)
        Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
}

或者您可以将相同的代码添加到动作过滤器中:

Or You could add the same code to an action filter:

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