redirect http to https asp net mvc

Redirect http to https ASP.Net MVC

Hello everyone, I am going to share the code sample for redirect http to https ASP.Net MVC projects using the different types of techniques. The techniques types as given belows.

Types 1: You can add the below code in Global.asax.cs for redirect http to https.

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

OR

Types 2: You can add the below code in Global.asax.cs for redirect http to https.

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 httpsPath = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
            Response.Status = "301 Moved Permanently.";
            Response.AddHeader("Location", httpsPath);
            break;
    }
}

OR

Types 3: You can add the below code to an action filter for redirect http to https.

public class SSL_Filters : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsSecureConnection)
        {
            var requestURL = filterContext.HttpContext.Request.Url.ToString().Replace("http:", "https:");
            filterContext.Result = new RedirectResult(requestURL);
        }
    }
}

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.