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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.