Created
May 26, 2011 14:17
-
-
Save robertmilne/993231 to your computer and use it in GitHub Desktop.
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
[RequireScheme(Scheme.Http)] | |
public partial class MyController : Controller | |
{ | |
public virtual ActionResult AllowsHttpOnly() | |
{ | |
return View(); | |
} | |
[RequireScheme(Scheme.Https)] | |
public virtual ActionResult AllowsHttpsOnly() | |
{ | |
return View(); | |
} | |
[RequireScheme(Scheme.Ignore)] | |
public virtual ActionResult AllowsHttpOrHttps() | |
{ | |
return View(); | |
} | |
} |
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
public enum Scheme | |
{ | |
Ignore, | |
Http, | |
Https, | |
} | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] | |
public class RequireScheme: FilterAttribute, IAuthorizationFilter | |
{ | |
private readonly Scheme scheme; | |
public RequireScheme(Scheme scheme) | |
{ | |
this.scheme = scheme; | |
} | |
public void OnAuthorization(AuthorizationContext filterContext) | |
{ | |
if ((scheme == Scheme.Https) && !filterContext.HttpContext.Request.IsSecureConnection) | |
filterContext.Result = GetResult(filterContext, "https"); | |
else if ((scheme == Scheme.Http) && filterContext.HttpContext.Request.IsSecureConnection) | |
filterContext.Result = GetResult(filterContext, "http"); | |
} | |
private static RedirectResult GetResult(AuthorizationContext filterContext, string scheme) | |
{ | |
var builder = new UriBuilder() | |
{ | |
Scheme = scheme, | |
Host = filterContext.HttpContext.Request.Url.Host, | |
Path = filterContext.HttpContext.Request.RawUrl | |
}; | |
return new RedirectResult(builder.ToString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment