Session in ASP.Net(C#) in Firefox and Chrome

2019-05-31 06:30发布

问题:

I would like to ask about the session lost after logout:

I wrote the code but it is only working in Internet Explorer and not in Mozilla Firefox or Google Chrome. In both of these browsers, after doing a logout if I click the back button, it is going back into the user's account.

Logout Page code (on page load)-

FormsAuthentication.SignOut();
Session.Abandon();
Session["CustomerId"] = null;
FormsAuthentication.RedirectToLoginPage();

In every other page or on master page-

Response.Cache.SetCacheability(HttpCacheability.NoCache);
if (Session["CustomerId"] == null)
{
    Response.Redirect("~/Login.aspx");
}

In web-config file-

<authentication mode="Forms">
   <forms name="MyCookie" loginUrl="Login.aspx" protection="All" timeout="90"    slidingExpiration="true"></forms>
</authentication>

回答1:

If you press back and you still see the user information's even if the user is logged out, is because you do not have take care the cache browser, so that the pages not cached by the browser.

To all the page that you do not wish to stay on browser cache you need to set:

CurrentPage.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(-4));
CurrentPage.Response.Cache.SetValidUntilExpires(false);
CurrentPage.Response.Cache.SetCacheability(HttpCacheability.NoCache);
CurrentPage.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
CurrentPage.Response.Cache.SetNoStore();
CurrentPage.Response.ExpiresAbsolute = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0));
CurrentPage.Response.Expires = 0;
CurrentPage.Response.CacheControl = "no-cache";
CurrentPage.Response.AppendHeader("Pragma", "no-cache");
CurrentPage.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate, post-check=0, pre-check=0");

Now the reason that IE not keep the data, and the other keep them is because of the setup that each browser select to work, or you have set. The point here is that you must have the control and not let the browser use the default settings if you like to avoid to keep this data in browser cache.

Also the HttpCacheability.NoCache alone maybe is enough for one browser but not enough for all. Also its better to use SSL because this pages may cached by proxy on the road...



回答2:

You need to check for the user session on the Page_init() event. If session is empty then redirect user to login page. so if you logout then and try to click on back button, then system will redirect user to login page not on that user account.

This is event where you need to check user session,

    protected void Page_init(object sender, EventArgs e)
    {
        if (Session["User"] == null)
        {
            Response.Redirect("Login.aspx");
        }
    }

Hope this will help you. Thank you.



回答3:

And you can hold your session alive with ajax or iframe.
Here is a simple example: keep session alive with iframe