简体   繁体   English

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

[英]How to redirect HTTP to HTTPS in MVC application (IIS7.5)

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.我需要将我的 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>

You can do it in code:你可以在代码中做到这一点:

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

In the Global.asax.cs :Global.asax.cs中:

Simple redirect简单重定向

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection
        && !Context.Request.IsLocal // to avoid switching to https when local testing
        )
    {
        // Only insert an "s" to the "http:", and avoid replacing wrongly http: in the url parameters
        Response.Redirect(Context.Request.Url.ToString().Insert(4, "s"));
    }
}

301 redirect: SEO best practice (Search Engine Optimization) 301重定向:SEO最佳实践(搜索引擎优化)

The 301 Moved Permanently redirect status response code is considered a best practice for upgrading users from HTTP to HTTPS ( see Google recommendations ). 301 Moved Permanently重定向状态响应代码被认为是将用户从 HTTP 升级到 HTTPS 的最佳实践(请参阅 Google 推荐)。

So if Google or Bing robots will be redirected too, consider this:因此,如果 Google 或 Bing 机器人也将被重定向,请考虑以下事项:

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection
        && !Context.Request.IsLocal // to avoid switching to https when local testing
        )
    {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", Context.Request.Url.ToString().Insert(4, "s"));
        Response.End();
    }
}

I use the following in Global.asax:我在 Global.asax 中使用以下内容:

protected void Application_BeginRequest()
{
  if (FormsAuthentication.RequireSSL && !Request.IsSecureConnection)
  {
    Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));
  }
}

I have the following ASP.NET MVC rewrite rule in Web.config file:我在 Web.config 文件中有以下 ASP.NET MVC 重写规则:

You can try this code with web.config file.您可以使用 web.config 文件尝试此代码。 If your URL is http://www.example.com then it will be redirect to this URL https://www.example.com .如果您的 URL 是http://www.example.com那么它将被重定向到这个 URL https://www.example.com

 <system.webServer> <rewrite> <rules> <rule name="http to https" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="^OFF$" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer>

You could use the RequireHttpsAttribute for simple cases.对于简单的情况,您可以使用 RequireHttpsAttribute。

[RequireHttps]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

As stated in MSDN...如 MSDN 中所述...

"Represents an attribute that forces an unsecured HTTP request to be re-sent over HTTPS." “表示强制通过 HTTPS 重新发送不安全的 HTTP 请求的属性。”

RequireHttpsAttribute RequireHttps属性

I'm not sure you'd want to use this to enforce HTTPS across a large site though.不过,我不确定您是否愿意使用它在大型网站上强制执行 HTTPS。 Lots of decorating to do, and opportunity to miss controllers.有很多装饰要做,还有机会错过控制器。

Use this code in web.config file for redirect http:// to https://在 web.config 文件中使用此代码将 http:// 重定向到 https://

<configuration>
  <system.webServer>
    <rewrite>
        <rules>
            <rule name="HTTPS force" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
   </system.webServer></configuration>

It's very simple.这很简单。 Just add one line in "Global.asax" file as below:只需在“Global.asax”文件中添加一行,如下所示:

protected void Application_Start()
{
    GlobalFilters.Filters.Add(new RequireHttpsAttribute(true));
}

If you would like to apply only server-side, not local side then apply following code:如果您只想应用服务器端,而不是本地端,请应用以下代码:

protected void Application_Start()
{
   if (!HttpContext.Current.Request.IsLocal)
         GlobalFilters.Filters.Add(new RequireHttpsAttribute(true));
}

Hope it will help you:) Thank you!希望对您有所帮助:)谢谢!

I did it thusly, since a local debug session uses custom port numbers:我是这样做的,因为本地调试会话使用自定义端口号:

    protected void Application_BeginRequest()
    {
        if (!Context.Request.IsSecureConnection)
        {
            if (HttpContext.Current.Request.IsLocal)
            {
                Response.Redirect(Context.Request.Url.ToString().Replace("http://localhost:25885/", "https://localhost:44300/"));
            }
            else
            {
                Response.Redirect(Context.Request.Url.ToString().Replace("http://", "https://"));
            }
        }
    }

Preferably there would be some way to get the URL and SSL URL programmatically...最好有某种方法以编程方式获取 URL 和 SSL URL ...

To force https only when the website is lunched on the server and ignore it while running the website on your machine for development:仅当网站在服务器上启动时强制使用 https,并在您的机器上运行网站进行开发时忽略它:

In Global.asax:在 Global.asax 中:

You'll need the Application_BeginRequest() method你需要 Application_BeginRequest() 方法

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
         // .....
    }

    //force https on server, ignore it on local machine
    protected void Application_BeginRequest()
    {
        if (!Context.Request.IsSecureConnection && !Context.Request.Url.ToString().Contains("localhost"))
            Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
    }
}

This answer is not exactly for OP but for those who could not make it work like me and have come across this (and although I know there is 403 not 404 error in OP), please refer to this answer if you are getting 404 instead: https://stackoverflow.com/a/6962829/5416602这个答案并不完全适用于 OP,但对于那些不能像我一样工作并且遇到过这个问题的人(虽然我知道 OP 中有 403 而不是 404 错误),如果你得到 404,请参考这个答案: https://stackoverflow.com/a/6962829/5416602

Please check that you have binding for HTTP port (80) and not only HTTPS port (443) in your IIS请检查您的 IIS 中是否绑定了 HTTP 端口 (80) 而不仅仅是 HTTPS 端口 (443)

I'm unable to add comments, but thought this supplementary info would maybe help somebody.我无法添加评论,但认为此补充信息可能会对某些人有所帮助。

I implemented the Global.asax idea with the 301 Permanent Redirect, and added http binding to the site in IIS.我用 301 永久重定向实现了 Global.asax 的想法,并在 IIS 中向网站添加了 http 绑定。 It still gave me 403 Forbidden until I remembered to untick "Require SSL" in SSL Settings.它仍然给了我 403 Forbidden,直到我记得在 SSL 设置中取消勾选“需要 SSL”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在IIS7.5中使用C#MVC从HTTP重定向到HTTPS并重定向到新域 - Redirect from HTTP to HTTPS and to a new domain with C# MVC in IIS7.5 mvc 4 + iis7.5应用程序停止 - mvc 4 + iis7.5 application stop IIS7.5和MVC 2:实现HTTP(S)安全 - IIS7.5 and MVC 2 : Implementing HTTP(S) security IIS7.5上的Maverick MVC-处理程序映射 - Maverick MVC on IIS7.5 - Handler mapping Application_Start() 在 IIS7.5 托管的 MVC 5 应用程序中调用两次 - Application_Start() called twice in IIS7.5 hosted MVC 5 application 在IIS7.5 HTTP 500 Internal Server Error上重新部署MVC5 dll - Redeployed MVC5 dlls on IIS7.5 HTTP 500 Internal Server Error IIS 7.5 URL重写-帐户控制器从http重定向到https,其他所有内容从https重定向到http - IIS 7.5 URL Rewrite - Redirect from http to https for account controller but from https to http for everything else 仅远程访问上出现HTTP错误401.0 IIS 7.5 MVC应用程序 - HTTP Error 401.0 IIS 7.5 MVC Application on remote access only 将MVC应用程序部署到IIS 7.5 - Deploy MVC Application to IIS 7.5 每次重新启动或发布网站时,如何在iis7.5上手动为asp.net mvc创建首次请求? - How manually create first request for asp.net mvc on iis7.5 when every time restart or release the website?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM