SSL pages under ASP.NET MVC

前端 未结 12 1110
情话喂你
情话喂你 2020-11-28 01:49

How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site?

Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Previe

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:34

    For those who are not a fan of attribute-oriented development approaches, here is a piece of code that could help:

    public static readonly string[] SecurePages = new[] { "login", "join" };
    protected void Application_AuthorizeRequest(object sender, EventArgs e)
    {
        var pageName = RequestHelper.GetPageNameOrDefault();
        if (!HttpContext.Current.Request.IsSecureConnection
            && (HttpContext.Current.Request.IsAuthenticated || SecurePages.Contains(pageName)))
        {
            Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
        }
        if (HttpContext.Current.Request.IsSecureConnection
            && !HttpContext.Current.Request.IsAuthenticated
            && !SecurePages.Contains(pageName))
        {
            Response.Redirect("http://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
        }
    }
    

    There are several reasons to avoid attributes and one of them is if you want to look at the list of all secured pages you will have to jump over all controllers in solution.

提交回复
热议问题