Moving between HTTP and HTTPS in ASP.NET MVC

前端 未结 2 1238
有刺的猬
有刺的猬 2020-12-28 22:49

So I\'ve found the [RequiresHttps] attribute but once your in https your kind of stuck there, so to try and be able to have actions on a single url (and scheme) I\'ve found

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 23:27

    What you have is syntatically correct, however a suggestion is to create a new Action filter that inherits from the default RequireHttpsAttribute and takes a parameter to switch between http and https.

    public class RequireHttpsAttribute : System.Web.Mvc.RequireHttpsAttribute
    {
        public bool RequireSecure = false;
    
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    
        {
            if (RequireSecure)
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                // non secure requested
                if (filterContext.HttpContext.Request.IsSecureConnection)
                {
                    HandleNonHttpRequest(filterContext);
                }
            }
        }
    
        protected virtual void HandleNonHttpRequest(AuthorizationContext filterContext)
        {
            if (String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                // redirect to HTTP version of page
                string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
                filterContext.Result = new RedirectResult(url);
            }
        } 
    }
    

    Then, on your action method or controller you would use:

    [RequireHttps (RequireSecure = true)]
    

    ...

    or

    [RequireHttps (RequireSecure = false)]
    

提交回复
热议问题