如何在MVC应用程序中将HTTP重定向到HTTPS(IIS7.5) [英] How to redirect HTTP to HTTPS in MVC application (IIS7.5)

查看:104
本文介绍了如何在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);
        }
    }
}

这篇关于如何在MVC应用程序中将HTTP重定向到HTTPS(IIS7.5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆