I just finished this ASP.NET MVC web application that required https for all requests. Here’s the approach I took to force https in the app.
Using the BeginRequest Method to Force Https
In the global.ascx.cs file (I used C# as the programming language), I decided to intercept all requests with the following Application_BeginRequest method:
protected void Application_BeginRequest() { if (!Context.Request.IsSecureConnection) { // This is an insecure connection, so redirect to the secure version UriBuilder uri = new UriBuilder(Context.Request.Url); if (!uri.Host.Equals("localhost")) { uri.Port = 443; uri.Scheme = "https"; Response.Redirect(uri.ToString()); } } }
In the method, I use the Request.IsSecureConnection property to check if the connection isn’t already using https. If the request isn’t over a secure connection and I’m not running the app on my development workstation, I instantiate an Uri object off the request’s Url and change the value of the port property to 443, the https port used by my production server. I also switch the Uri’s scheme to https. Finally, I redirect the request to the updated Uri.
That’s it.
Alternative Approaches
There are other approaches you can take to force https in ASP.NET MVC. For example, you can decorate the controller methods that require https with the RequireHttpsAttribute attribute, which will force https connections for those methods, even in your development environment. You can also derive from the RequireHttpsAttribute Class and create an attribute that will force https for remote connections only:
public class RequireHttpsForRemoteRequestAttribute : RequireHttpsAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.HttpContext.Request.IsLocal) { // Don't require HTTPS for local requests. return; } base.OnAuthorization(filterContext); } }
Over to You
Your turn now. Do you use https in your ASP.NET MVC apps? How to you set it up? Leave a comment with your thoughts below.
Thanks for share the code; My question is how to switch between http and https in an app? For my case I need https for most of pages, for some of pages like maps I’d like to use http because the data is too heavy, unlike Google map, Bing Map, my map has several hundred layers for users to interactive with these layers’ information. In previous web form, I can write some rules in configure file, is this still can be used in MVC? Thanks.