Last active
December 11, 2015 06:18
-
-
Save carolynvs/4558181 to your computer and use it in GitHub Desktop.
RequireHttp attribute allows redirecting back to HTTP after visiting a secured page. Enables mixing secured and unsecured pages in ASP.NET MVC.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Forces a secured (HTTPS) request to be resent over HTTP | |
/// </summary> | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] | |
public class RequireHttpAttribute : FilterAttribute, IAuthorizationFilter | |
{ | |
public virtual void OnAuthorization(AuthorizationContext filterContext) | |
{ | |
if(filterContext == null) | |
{ | |
throw new ArgumentNullException("filterContext"); | |
} | |
if(!filterContext.HttpContext.Request.IsSecureConnection) | |
{ | |
return; | |
} | |
HandleHttpsRequest(filterContext); | |
} | |
protected virtual void HandleHttpsRequest(AuthorizationContext filterContext) | |
{ | |
if(!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) | |
{ | |
// Only redirect GET requests | |
return; | |
} | |
string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; | |
filterContext.Result = new RedirectResult(url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment