2

I am developing an ASP.Net MVC 3 Web Application. I need to have my website secured with an SSL certificate, however, I only want this used when the application is on my live server, NOT on my test server.

Therefore, I setup an AppSetting in my Web Config like so

<appSettings>
    <add key="SSL" value="false" />
</appSettings>

Then in my Account Controller I get this value (either True or False) and using the value, decide whether or not to set the RequiresHttps attribute on my LogOn Action. I would like to do something like so

public class AccountController : Controller
{
        public string SSL = System.Configuration.ConfigurationManager.AppSettings["SSL"];

        if (SSL.Equals("true"))
        {
            [RequireHttps]
        }
        public ActionResult LogOn()
        {
            return View();
        }
}

But I know I can't put my IF statement where it currently is, however, hopefully you get the idea of what I am trying to achieve.

Does anyone have any suggestions as to how I can implement my idea?

Thanks.

tcode
  • 5,055
  • 19
  • 65
  • 124
  • Could this help you ? http://stackoverflow.com/questions/7846833/why-once-ssl-is-enabled-with-requirehttps-at-action-level-it-remains-enabled – Niklas Oct 10 '12 at 09:14

1 Answers1

1

Subclass the RequireHttpAttribute (note this code is changed from my original answer - this new version will be more efficient):

public class RequireHttpsIfEnabledAttribute : RequireHttpsAttribute
{
  //this setting can't be changed without a recycle, so get it once and cache it.
  private static readonly Lazy<bool> HttpsRequired = new Lazy<bool>(() => {
    //if the AppSettings["SSL"] returns null you raise an exception if you do a
    //.Equals on it - so do it on the constant instead.  And make sure it's case
    //insensitive!
    return "true".Equals(System.Configuration.ConfigurationManager.AppSettings["SSL"],
      StringComparison.OrdinalIgnoreCase);
  });
  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    //calling the base will fire the HTTPS check.  Not calling it will allow
    //non-SSL requests through
    if (HttpsRequired.Value)  
      base.OnAuthorization(filterContext);
  }
}

Now you just decorate your controllers/actions as before - but with your new attribute:

[RequireHttpsIfEnabled]
public class AccountController : Controller 
{
  //....
}
Andras Zoltan
  • 41,961
  • 13
  • 104
  • 160