How to redirect HTTP to HTTPS in MVC application (

2019-01-10 09:27发布

问题:

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>

回答1:

I use the following in Global.asax:

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


回答2:

You can do it in code:

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


回答3:

In the 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)

The 301 Moved Permanently redirect status response code is considered a best practice for upgrading users from HTTP to HTTPS (see Google recommendations).

So if Google or Bing robots will be redirected too, consider this:

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


回答4:

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



回答5:

You could use the RequireHttpsAttribute for simple cases.

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

As stated in MSDN...

"Represents an attribute that forces an unsecured HTTP request to be re-sent over HTTPS."

RequireHttpsAttribute

I'm not sure you'd want to use this to enforce HTTPS across a large site though. Lots of decorating to do, and opportunity to miss controllers.



回答6:

To force https only when the website is lunched on the server and ignore it while running the website on your machine for development :

In Global.asax :

You'll need the Application_BeginRequest() method

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