简体   繁体   中英

Redirect automatically to the login when the session is expired

I am using the .NET framework 4.5

I have set the sessionState to expire after 60 minutes. Every pages that require to be "logged" inherits from a class named BasePage.cs . On the OnPreInit event, this class verify the Session object and redirect to the login page when the session is expired.

Here is the configuration of the sessionState (web.config) :

<sessionState timeout="60"/>

Here is my verification in the class "BasePage.cs" :

protected override void OnPreInit(EventArgs e)
{
    if (HttpContext.Current.Session["infosession"] == null)
    {
        Response.Redirect("default.aspx");
    }

}

This verification is working great when the user is navigating trough the pages.

In some pages, I am using a WCF Service (Ajax-enabled) called from javascript. Between the time the pages will be generated and the time the WCF Service will be called, the session may expire. Given that I should not assume that my Wcf Service's consumer will be a particular kind of software or have certain capabilities, as been a web browser, I can't do the verification there .

So after some explanations, here the question :

Is it possible, when the session expire (after 60 mins), to redirect automatically to the login page ?

why not do something like the following instead

public static string Infosession 
{ 
    get 
    {
        object value = HttpContext.Current.Session["infosession"];
        return value == null ? "" : (string)value;
    }
    set 
    {
        HttpContext.Current.Session["infosession"] = value;
    }
}

I would initialize the value in the OnSessionStart() in the Global.asax.cs file

HttpContext.Current.Session["infosession"] = string.Empty;

I would move this code protected override void OnPreInit to the Page_Load() event

another alternative

protected void Page_load(EventArgs e)
{
    if (HttpContext.Current.Session["infosession"] == string.Empty)
    {
        Response.Redirect("default.aspx");
    }
}

Assuming you are looking for client side solution - just set timer to expiration time (ie 1 hour) and How can I refresh a page with jQuery? :

 reloadTimer = setTimeout(60*60*1000, function() { location.reload();}

You may want to reset the timer if you get AJAX updates on the page that reset the session timeout.

Note that it no going to stop one from calling your WCF service directly, so it is not security measure but rather convenience.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM