ASP.NET: best practice for redirecting to https

后端 未结 4 1481
你的背包
你的背包 2021-02-02 03:21

I am working on a project that has one page that needs to make use of the SSL certificate. All of the links in the site to this page make use of https instead of http, but in th

4条回答
  •  天涯浪人
    2021-02-02 03:43

    Generally, there are specific parts of the site that you either want to always be HTTPS, or HTTP.

    I use the following action attribute to convert the traffic either to one or another:

    public class ForceConnectionSchemeAttribute : ActionFilterAttribute
    {
        private string scheme;
    
        public ForceConnectionSchemeAttribute(string scheme)
        {
            this.scheme = scheme.ToLower();
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Uri url = filterContext.HttpContext.Request.Url;
            if (url.Scheme != scheme)
            {
                string secureUrl = String.Format("{0}://{1}{2}", scheme, url.Host, url.PathAndQuery);
                filterContext.Result = new RedirectResult(secureUrl);
            }
        }
    }
    
    
    // Suppose I always want users to use HTTPS to access their personal info:
    [ForceConnectionScheme("https")]
    public class UserController: Controller
    {
        // blah
    }
    

提交回复
热议问题