开发者

Detect when a users session has exipred

开发者 https://www.devze.com 2023-01-01 13:51 出处:网络
Can anyone tell me how to detect when a users 开发者_如何学JAVAsession has exipred in asp? I want to redirect users to a logged out page once the session has expired

Can anyone tell me how to detect when a users 开发者_如何学JAVAsession has exipred in asp?

I want to redirect users to a logged out page once the session has expired

Thanks Sp


I suppose you have to implement the session check on a group of pages of your site, so a good way to do that is to declare a base class for all your "restricted access" pages. Something like:

public class BasePage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (Session["Context"] == null) 
        {
            // do redirect
        }
    }
}

supposing that, on login, you'll assign an object representing the session to Session["Context"]

Your pages will inherit this class as:

public partial class _Default : BasePage { ... }


Use the Session_End() function in your global.asax file. Please see here for more info

SO - Session End

EDIT: Nope, that probably won't do it. See comments below.

If you must redirect on a session expiration, would something like this do the trick for you?

private void Page_Load(object sender, System.EventArgs e)
{ 

Response.AddHeader(“Refresh”,Convert.ToString((Session.Timeout * 60) + 5)); 
if(Session[“IsUserValid”].ToString()==””) 
Server.Transfer(“Relogin.aspx”);

}

EDIT 2: Caveat, this can get tricky if you have AJAX stuff going on.

I have seen examples where people will put this in the page_load of a base page and inheirit all of your .aspx pages from this base page. This prevents you from having to add this code for every single page that you have.

Why won't the first method work (Session_End)? This is a function called internally on the server when a session ends. As such, there is no associated request/response to redirect or transfer. I.e., this function could be called by the server 20 minutes after you close the browswer.


You can check the HttpContext.Current.User.Identity.IsAuthenticated property which will allow you to know whether there's a currently authenticated user or not.

so on ur page load

if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //FormsAuthentication.RedirectToLoginPage();
                Response.Redirect("~/Login.aspx");
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消