How to easily redirect from http to https in ASP.NET

by APIJunkie 23. February 2008 09:58

Below is a simple code snippet to redirect from a non secure HTTP URL to a secure HTTPS URL using C# and ASP.NET.

The code checks if we are using a secure connection and if not it redirects to the same requested URL changing the protocol from HTTP to HTTPS.

////////////////////////////////////////////////////////////////

// Check if we are using https and if not redirect

///////////////////////////////////////////////////////////////

if(!Request.IsSecureConnection)

{

 
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");

  Response.Redirect(redirectUrl);

}

 

Tags:

ASP.NET | How To | Web Development

Comments

2/23/2008 10:05:34 AM #

trackback

Trackback from DotNetKicks.com

How to easily redirect from http to https in ASP.NET

DotNetKicks.com

3/27/2008 8:43:15 PM #

fosiul

Hi, your code is good, but there is one problem
when i am going out from https page to another page which is actually http, its not going to http, its always staying in https for rest of the pages.

i understand, now i will have to write a code to go to https to http for other pages aswell. which  would be problamatic, its not it ?

is not there any other way to write code for http to https redirection ?

fosiul United Kingdom

3/28/2008 12:53:37 AM #

APIJunkie

Hi Fosiul,
Thank you for your comment.
I have compiled a new blog entry to try and further address the issue of easy transitions from HTTP to HTTPS and vice versa.

www.apijunkie.com/.../post.aspx

APIJunkie United States

Comments are closed

About the author

Name of author

I was first wounded by x86 assembly, recovered and moved on to C. Following a long addiction to C++ and a short stint at rehab I decided to switch to a healthier addiction so I am now happily sniffing .NET and getting hooked on Silverlight.

I am mainly here to ramble about coding, various API’s, Junkies(me especially) and everything else that happens between coders and their significant other.

  James Bacon