Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect from http to https in asp.net C# and make it as default version for the website

how to redirect from http to https in asp.net c# i have installed https certificate now i want to make https as default version for my website iam using windows server 2008 R2 asp.net C# 4.0

like image 423
user2765331 Avatar asked Oct 20 '13 06:10

user2765331


2 Answers

Are you looking for something like this:-

if (!Request.IsLocal && !Request.IsSecureConnection)
{
    string sUrl = Request.Url.ToString().Replace("http:", "https:");
    Response.Redirect(sUrl);
}

Also check this related forum.

From the above link:-

You can install URL Rewrite Module, create a redirect rule and put it to your web.config file

<rule name="http to https" stopProcessing="true">
     <match url=".*" />
     <conditions>
     <add input="{HTTPS}" pattern="off" />
     </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" />
 </rule>
like image 86
Rahul Tripathi Avatar answered Oct 19 '22 21:10

Rahul Tripathi


A far cleaner/easier way of doing it than mentioned above is to use the RequireHttpsAttribute class within the System.Web.Mvc package.

Simply register the attribute by adding it to the FilterConfig.RegisterGlobalFilters() method that's invoked inside of Global.asax.cs like so:

FilterConfig.cs

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new RequireHttpsAttribute());
    }
}

This will register the RequireHttps attribute across all controller classes, forcing it to redirect to HTTPS if it isn't already doing so.

Note: This is only applicable to ASP.NET MVC and not WebAPI.

like image 20
Joseph Woodward Avatar answered Oct 19 '22 20:10

Joseph Woodward