1 namespace System.Web.Mvc { 2 using System; 3 using System.Diagnostics.CodeAnalysis; 4 using System.Web.Mvc.Resources; 5 6 [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "Unsealed because type contains virtual extensibility points.")] 7 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 8 public class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter { 9 OnAuthorization(AuthorizationContext filterContext)10 public virtual void OnAuthorization(AuthorizationContext filterContext) { 11 if (filterContext == null) { 12 throw new ArgumentNullException("filterContext"); 13 } 14 15 if (!filterContext.HttpContext.Request.IsSecureConnection) { 16 HandleNonHttpsRequest(filterContext); 17 } 18 } 19 HandleNonHttpsRequest(AuthorizationContext filterContext)20 protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) { 21 // only redirect for GET requests, otherwise the browser might not propagate the verb and request 22 // body correctly. 23 24 if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { 25 throw new InvalidOperationException(MvcResources.RequireHttpsAttribute_MustUseSsl); 26 } 27 28 // redirect to HTTPS version of page 29 string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; 30 filterContext.Result = new RedirectResult(url); 31 } 32 33 } 34 } 35