asp.net c# redirecting from http to https

I’d do a !Request.IsLocal as well to make sure that I’m not debugging, though if you’re using a real instance of IIS with a cert applied when debugging that shouldn’t be an issue.

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

Note: This answer assumes an MVC context within a Controller where HttpContext is a property holding the current context. If you’re unlucky enough to still be using WebForms or are referencing the context in a degenerate way you will need to use HttpContext.Current.ApplicationInstance.CompleteRequest().

Note: I’ve updated this to be consistent with the recommended pattern to terminate the request according to the framework documentation.

When you use this method in a page handler to terminate a request for
one page and start a new request for another page, set endResponse to
false and then call the CompleteRequest method. If you specify true
for the endResponse parameter, this method calls the End method for
the original request, which throws a ThreadAbortException exception
when it completes. This exception has a detrimental effect on Web
application performance, which is why passing false for the
endResponse parameter is recommended. For more information, see the
End method.

Leave a Comment