加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何重定向HTTP到HTTPS在MVC应用程序(IIS7.5)

发布时间:2020-12-15 19:13:37 所属栏目:asp.Net 来源:网络整理
导读:我需要重定向我的HTTP站点到HTTPS,已添加以下规则,但我得到403错误时尝试使用 http://www.example.com,它工作正常,当我在浏览器中键入 https://www.example.com。 system.webServer rewrite rules rule name="HTTP to HTTPS redirect" stopProcessing="t
我需要重定向我的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);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读