So in my code I want to detect if my login page is being called http, and redirect it to https.
I know there are non code ways to skin this cat, but for frustrating technical reasosn I'm backed into doing it in code.
if (!Request.IsSecureConnection)
{
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl);
}
So I drop this in my Page_Load(...)
, make sure my debugger uses real IIS, not VS2008s IIS, and hit debug.
Inthe debugger, waltz along, hit Response.Redirect("https://localhost/StudentPortal3G/AccessControl/AdLogin.aspx"), hit f5.
Get "Internet Explorere Cannot Display the webpage, url is HTTP, not HTTPS. Not getting an informative error... same thing happens not running in the debugger.
So what am I missing? it does not appear to be rocket science, I've seen similar code on lots of blogs...
What am I doing wrong? I figure it has to be a totally obvious Rookie mistake, but I'm not seeing it.
I would also suggest tvalfonsso's solution, but with a small modification in case you have some url rewriting (RawUrl differs from Url)
In my opinion the following is the best all-round approach.
Three reasons
MVC
andWeb API
as it is done atIIS
level.https
sites on your pc).https
Simply add the following to your
<system.webServer>
section in your 'Web.config' for your project.On my development environment, I like to have a separate publish directory with IIS installed with a self signed cert, which is different form my code directory without a cert that I debug directly inside of Visual Studio. In this scenario
!Request.IsLocal
isn't ideal because it doesn't work anywhere on your development environment, even in the IIS directory with the cert. I prefer this:HttpContext.Current.IsDebuggingEnabled
is based on the value of compilation debug="true/false" in your web.config. I have it set to true in my code directory, and false in my publish directory when I need to test http and https redirection locally.I add in the
IsPostBack
simply to make it (slightly) more efficient by skipping the extra ssl checking when not needed.