ASP.NET MVC RequireHttps in Production Only

Viewed 43967

I want to use the RequireHttpsAttribute to prevent unsecured HTTP requests from being sent to an action method.

C#

[RequireHttps] //apply to all actions in controller
public class SomeController 
{
    [RequireHttps] //apply to this action only
    public ActionResult SomeAction()
    {
        ...
    }
}

VB

<RequireHttps()> _
Public Class SomeController

    <RequireHttps()> _
    Public Function SomeAction() As ActionResult
        ...
    End Function

End Class

Unfortunately, ASP.NET Development Server doesn't support HTTPS.

How can I make my ASP.NET MVC application use RequireHttps when published to the production environment, but not when run on my development workstation on the ASP.NET Development Server?

16 Answers

You can set in global.asax to use SSL only. Then use #if !DEBUG to avoid using RequireHttpsAttribute() it on local

public class MvcApplication : System.Web.HttpApplication
    { 
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas(); 
  WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
    #if !DEBUG
            GlobalFilters.Filters.Add(new RequireHttpsAttribute());
     #endif
        }
}
Related