Skip to content

Instantly share code, notes, and snippets.

@robertmilne
Created May 26, 2011 14:17
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 robertmilne/993231 to your computer and use it in GitHub Desktop.
Save robertmilne/993231 to your computer and use it in GitHub Desktop.
[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();
}
}
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