Skip to content

Instantly share code, notes, and snippets.

@carolynvs
Last active December 11, 2015 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carolynvs/4558181 to your computer and use it in GitHub Desktop.
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.
/// <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