.NET: Redirect Non-SSL HTTP Requests to SSL HTTPS Requests in ASP/MVC

5/20/2015 9:31:48 PM

You can force .NET using both Webforms and MVC to redirect all non-ssl requests to ssl requests. You will probably want a parameter to control whether this is done to allow different ssl behavior in different staging environments.

protected void Application_BeginRequest()
{						
	//redirect to https
	string url = HttpContext.Current.Request.Url.ToString();                        
	bool forceSSL = false;

	//dont redirect to ssl on localhost
	//could also set up a appsetting to control when to force ssl
	forceSSL = !url.Contains("localhost");

	if (forceSSL)
	{				
		string scheme = HttpContext.Current.Request.Url.Scheme;
		if (!url.StartsWith("https://"))
		{
			string newUrl = url.Replace("http://", "https://");
			Response.Redirect(newUrl);
		}				
	}
}