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
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With