How to redirect from HTTP to HTTPS in asp.net?


How can I redirect HTTP(not secured) to HTTPS(Secured domain) URL  in asp.net, here is my current code, which I am using in web.config

<configuration>
<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="Permanent" url="https://{HTTP_HOST}/{R:1}" />
</rule>   
    </rules>
</rewrite>
</system.webServer>
</configuration>

After adding this code in web.config, I got an error "Not Secured"


Asked by:- RameshwarLate
1
: 13106 At:- 10/21/2017 7:44:59 AM
asp.net web.config system.web system.webServer http-to-https







3 Answers
profileImage Answered by:- bhanu

Using web.config you can ask IIS to redirect to HTTPS using the code below (You will need to download and install IIS URL rewrite)

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

Now, remember on server, you should bind your application to :443 port (which is used for https)

Login to you server-> Open IIS-> Expand server(Win---) -> Expand Sites -> Select Your Website -> In the right hand side pane (Actions Tabs) -> Click on Bindings -> Select "Add" -> Edit Site Bindings Details  -> Click "ok"

how-to-redirect-from-http-to-https-in-aspnet

<add input=”{HTTPS}” pattern=”off” ignoreCase=”true” /> is the main redirection rule that redirects HTTP requests to HTTPS (this is called 301 redirection)

In IIS 10 and Windows Server 2016

In IIS10 (Windows 10 and Server 2016), from version 1709 onwards, there is a new, simpler option for enabling HSTS for a website.

By Editing applicationhost.config file directly Between the <site> tags, add this line:

<hsts enabled="true" max-age="31536000" includeSubDomains="true" redirectHttpToHttps="true" />

In ASP.NET Core

In Program.cs (.NET Core 6), you can simply add below line of code

var builder = WebApplication.CreateBuilder(args);

// ...existing code...

var app = builder.Build();

app.UseHttpsRedirection();  // HTTPS redirection

The UseHttpsRedirection() method invocation enables the HTTPS redirection middleware. This means that each request to your application will be inspected and possibly redirected by the middleware.

3
At:- 10/26/2017 4:55:24 AM Updated at:- 10/19/2022 7:52:27 AM
IIS redirect from http to https is easier and can be done easily, but it requires to install URL rewrite module on IIS first. 0
By : neena - at :- 6/13/2021 3:22:53 PM


profileImage Answered by:- vikas_jk

Try this code in your Global.asax (without using Web.config approach)

protected void Application_BeginRequest(Object sender, EventArgs e)
{
  switch (Request.Url.Scheme)
  {
    case "https":
      Response.AddHeader("Strict-Transport-Security", "max-age=300");
      break;
    case "http":
      var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location", path);
      break;
  }
}

The above code is using HSTS by returning the "Strict-Transport-Security" header to the browser

Or try this code 

protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
   {
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+   HttpContext.Current.Request.RawUrl);
   }
}

One of them will work if you are on ASP.NET web forms website

For those who are using ASP.NET MVC & came across this question, you can use these 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);
        }
    }
}
1
At:- 10/21/2017 10:40:41 AM


profileImage Answered by:- vikas_jk

I have found one more better way to redirect user from http to https in ASP.NET MVC

You can create a CustomRequireHttpsFilter class for handling Request

public class CustomRequireHttpsFilter : RequireHttpsAttribute
{
    protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
    {
        // The base only redirects GET, but we added HEAD as well. This avoids exceptions for bots crawling using HEAD.
        // The other requests will throw an exception to ensure the correct verbs are used. 
        // We fall back to the base method as the mvc exceptions are marked as internal. 

        if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) 
            && !String.Equals(filterContext.HttpContext.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
        {
            base.HandleNonHttpsRequest(filterContext);
        }            

        // Redirect to HTTPS version of page
        // We updated this to redirect using 301 (permanent) instead of 302 (temporary).
        string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;

        if (string.Equals(filterContext.HttpContext.Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
        {                
            // For localhost requests, default to IISExpress https default port (44300)
            url = "https://" + filterContext.HttpContext.Request.Url.Host + ":44300" + filterContext.HttpContext.Request.RawUrl;
        }

        filterContext.Result = new RedirectResult(url, true);
    }
}

and then use it as below in FilterConifg.cs

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
       //add filter
        filters.Add(new CustomRequireHttpsFilter());
    }
}
1
At:- 10/28/2018 12:44:29 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use