6

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

2 Answers 2

15

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>
Sign up to request clarification or add additional context in comments.

6 Comments

yeah can i add anything like this in web.config file
how can i install rewrite module am getting an error while adding this in web.config
thank 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
simple "Response.Redirect" works great but "config Rule" in production II7 not.
|
12

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.

4 Comments

I believe this is the cleanest and easiest way.
Does this also apply to Web API controllers?
No, 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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.