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

标签 asp.net-mvc http redirect 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>

最佳答案

你可以在代码中做到这一点:

全局.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);
        }
    }
}

关于asp.net-mvc - 如何在 MVC 应用程序中将 HTTP 重定向到 HTTPS (IIS7.5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4945883/

相关文章:

java - 通过Java将sqlite数据库连接到http服务器

angular - 授权 header 未通过 HTTPS 加密

reactjs - 如果用户访问 Next.js 中的特定 URL,如何重定向到另一个页面?

asp.net-mvc - ApiController 如何接受多个变量?

c# - 如何配置 UseSqlServer?

c# - 如何在不使用模型的情况下使用 Entity Framework 执行原始 SQL 查询?

java - 如何在REST应用程序中获取 "X-Forwarded-Proto" header ?

php - Codeigniter 的 redirect() 和非标准 url

HTTP:重定向时,服务器是否立即发送响应?

asp.net-mvc - ASP.NET MVC 中的四个文件结果有什么区别