Unfortunately ASP.NET doesn't provide a nice out of the box solution for handling the session timeout gracefully. Everything expires behind the scenes and your user is left unaware of what has happened. Additional problems can arise if the user abandoned their browser in a state that you didn't code for, which can result in errors or exceptions taking place.
With this in mind I like to put a Session Expired page in place in my applications and pro-actively send the user there when their session ends. This accomplishes a few different things:
1) Provides a nice user experience for your users
2) Prevents your application from being left in an unknown state when the session / auth ticket expires
3) Prevents application errors and exceptions from occurring when a user tries to perform an action on a page after their session / auth ticket has expired
Nested MasterPage(s) For All Authenticated Pages
You need to implement a MasterPage (or a Page base class) for all of your authenticated pages so you can inject a bit of javascript to handle the redirect on session timeout.
Get Your Web.config Settings Straight
Make sure that your auth ticket timeout and session timeout match.
protection="All"
path="/"
requireSSL="false"
timeout="45"
name=".ASPXAUTH"
slidingExpiration="true"
defaultUrl="Login.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
Create Your Session Expiration Page
Create a page for your users to be taken to when their session expires. I created SessionExpired.aspx with the following message:
Session Expired
Your session has expired due to inactivity.
Click here to login again
Ensure the Authentication ticket is signed out in your code behind:
FormsAuthentication.SignOut();
Add The Session Expiration Javascript To Your Page_Load
In the Page_Load method of your MasterPage (or base page class) add the following code:
// Handle the session timeout
string sessionExpiredUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/SessionExpired.aspx";
StringBuilder script = new StringBuilder();
script.Append("function expireSession(){ \n");
script.Append(string.Format(" window.location = '{0}';\n", sessionExpiredUrl));
script.Append("} \n");
script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000)); // Convert minutes to milliseconds
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true);
That's It
The session timeout script should be injected into each of your authenticated pages now. The client's browser will begin the countdown after each page has loaded or each PostBack has occurred. Once the countdown is reached the browser will redirect to your SessionExpired page.
Reference:
http://msmvps.com/blogs/shahed/archive/2007/09/05/redirect-to-login-page-on-session-expiration-asp-net.aspx
Aaron Schnieder
http://www.churchofficeonline.com
No comments:
Post a Comment