Skip to content

Instantly share code, notes, and snippets.

@artiomchi
Last active December 23, 2015 23:49
Show Gist options
  • Save artiomchi/6712075 to your computer and use it in GitHub Desktop.
Save artiomchi/6712075 to your computer and use it in GitHub Desktop.
RequireHttpsPermanentAttribute - a subclass of the RequireHttpsAttribute that also allows HEAD requests and does a permanent redirect
/// <summary>
/// Same as the standard RequireHttps attribute, except the redirect is permanent,
/// and it doesn't throw exceptions for a HEAD request
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class RequireHttpsPermanentAttribute : RequireHttpsAttribute
{
private static String[] _allowedMethods = new[] { "GET", "HEAD" };
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
if (!_allowedMethods.Contains(filterContext.HttpContext.Request.HttpMethod, StringComparer.OrdinalIgnoreCase))
{
throw new InvalidOperationException("The requested resource can only be accessed via SSL.");
}
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment