Last active
December 23, 2015 23:49
-
-
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
This file contains 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> | |
/// 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