Create a gist now

Instantly share code, notes, and snippets.

[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