I am converting an asp.net application into mvc3. Lets say I have a sign in page that requires https and every other page only needs http how can I redirect the signin to ht
A co-worker of mine and I looked at this and believe we found a good solution. Here is what we came up with:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class HttpsRequiredAttribute : RequireHttpsAttribute
{
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
// Check to see if we're secure
string requirestr = ConfigurationManager.AppSettings["RequireHttps"];
bool require;
if (bool.TryParse(requirestr, out require) && require)
base.HandleNonHttpsRequest(filterContext);
}
}
This works by extending the RequireHttpsAttribute, and can be applied to a class or method, as indicated by the AttributeTargets. We then overrode the virtual function in RequireHttpsAttribute. What the method does is check the Web.config file for a key called "RequireHttps". If it cannot find it, or it's an invalid bool value (which is what the bool.tryparse checks), then it does not require Https. If it finds the value as true, then it requires HTTPS.
If you use this extension, you'll need to add a key in your Web.config called "RequireHttps," like so:
You can then turn off the requirement for Https by changing this variable for when you're debugging, or by changing your Web.config file to have the requirement wherever your site is deployed.