How can I have ASP.NET automatically redirect non-logged in Forms users to the login page?

前端 未结 4 1764
谎友^
谎友^ 2021-02-07 09:35

I have an ASP.NET website.

I want users who are not logged in to be automatically (re)directed to the login page, for example,

~/Account/Login.aspx
         


        
4条回答
  •  既然无缘
    2021-02-07 10:10

    If you wish to force for all pages all used to be first logged in, you can capture the authentication request on global.asax and make this programmatically as:

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        // This is the page
        string cTheFile = HttpContext.Current.Request.Path;
    
        // Check if I am all ready on login page to avoid crash
        if (!cTheFile.EndsWith("login.aspx"))
        {
            // Extract the form's authentication cookie
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];
    
            // If not logged in
            if (null == authCookie)
            // Alternative way of checking:
            //     if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("/login.aspx", true);
                Response.End();
                return;
            }
        }
    }
    

    This code is called on every page and checks all pages on your site.

提交回复
热议问题