how to redirect from http to https in asp.net C# and make it as default version for the website
Solution 1
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>
Solution 2
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.
Related videos on Youtube
user2765331
Updated on September 15, 2022Comments
-
user2765331 about 1 year
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
-
user2765331 about 10 yearsyeah can i add anything like this in web.config file
-
Rahul Tripathi about 10 years@user2765331:- Updated my answer. Does that help?
-
user2765331 about 10 yearshow can i install rewrite module am getting an error while adding this in web.config
-
Rahul Tripathi about 10 yearsCheck this:- iis.net/learn/extensions/url-rewrite-module/…
-
user2765331 about 10 yearsthank you very much tripati the first code is working fine now does it has any flaws or anything to be taken care while using that code
-
BGBRUNO about 9 yearssimple "Response.Redirect" works great but "config Rule" in production II7 not.
-
mcy almost 8 yearsI believe this is the cleanest and easiest way.
-
Richard Ev over 7 yearsDoes this also apply to Web API controllers?
-
Joseph Woodward over 7 yearsNo, this doesn't apply to Web API controllers. I would imagine the correct way to handle this in WebAPI would be to send the appropriate response code informing the client or consumer of the API that HTTPS is required. The onus would then be on the client to ensure they're using HTTPS.
-
Joseph Woodward about 7 years@Zapnologica I'm afraid I can't remember. I believe it does - but it's been a while since I've used it so I can't be certain.
-
Zapnologica about 7 yearsI have another example where the action type is
..{R:1}
and yours is{R:0}
what does that number mean?