How to Check whether Session is Expired or not in asp.net

前端 未结 8 2117
情话喂你
情话喂你 2020-12-03 01:03

I\'ve specified the session timeout in web.config file. When the session is timeout I\'m not getting redirect to the login page but I am getting an error saying object refer

8条回答
  •  情话喂你
    2020-12-03 01:29

    Use Session.Contents.Count:

    if (Session.Contents.Count == 0)
    {
        Response.Write(".NET session has Expired");
        Response.End();
    }
    else
    {
        InitializeControls();
    }
    

    The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["user_id"] = 1;
    }
    

    Best of luck to you!

提交回复
热议问题