Check Session variable and Redirect to login page before page load

后端 未结 4 1421
旧时难觅i
旧时难觅i 2021-01-07 13:05

How can I check a variable and redirect to another page before the page loads using ASP.NET?

I\'m aware of the life cycle, and PageInit() sounds like it

4条回答
  •  长情又很酷
    2021-01-07 13:15

    I suggest you take the time to read up about Asp.Net membership. Then if you need to, implement your own MembershipProvider that will take care of the necessary plumbing with regards to authenticating user requests.

    The membership abstraction is really useful and implementing your own provider is really not that difficult.

    That said, if you really want to use a value from the Session to manage authentication, you could try to put the code in the Application_PostAcquireRequestState method in Global.asax. That way your code will automatically be called for (almost) all request to your application, and it is also the first available event where the session is available (as far as I know). Sample:

    void Application_PostAcquireRequestState(object sender, EventArgs e)
    {
        if (Session["LoggedUserName"] == null && !Request.Path.EndsWith("login.aspx"))
        {
            Response.Redirect("~/your/path/login.aspx");
        } 
    }
    

提交回复
热议问题