MaxCoder88
MaxCoder88

Reputation: 2428

How to configure a site to redirect automatically from HTTP to HTTPS in C#

I set up SSL for my web site about one month ago.However,I have not never been used to that on the web site. These are my problems:

Code:

protected void Page_Load(object sender, EventArgs e)
{

    Response.Clear();
    Response.Buffer = true;
    //  Response.ContentEncoding = System.Text.Encoding.Default;
    Response.ContentType = "text/html; charset=windows-1254";

    if (Request.Url.Scheme == "https")
    {
        string URL = Request.Url.ToString();
        URL = URL.Replace("https://", "http://");
        Response.Redirect(URL);
    }
}

My question is:how to configure a site to redirect automatically from HTTP to HTTPS in C#?

Upvotes: 1

Views: 1851

Answers (3)

user1519979
user1519979

Reputation: 1874

Personally i prefer the Url-Rewrite Module for IIS: https://www.iis.net/downloads/microsoft/url-rewrite

After installing the moudle you can add the redirect in web.config:

<system.webServer>
    <rewrite>
        <rules>
                <clear />
                <rule name="https" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{HTTPS}" pattern="off" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
                </rule>
        </rules>
    </rewrite>
  </system.webServer>

Upvotes: 0

biluriuday
biluriuday

Reputation: 428

In Application_BeginRequest method of Global.asax page, check if the request is http. If so, replace the http with https:

if (!HttpContext.Current.Request.IsSecureConnection)
{
    string redirectUrl = HttpContext.Current.Request.Url.ToString().Replace("http:", "https:");
    HttpContext.Current.Response.Redirect(redirectUrl);
}

Upvotes: 0

CB.
CB.

Reputation: 60938

Check if http redirects to https:

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

Upvotes: 2

Related Questions