Wednesday, September 30, 2009

Managing Session Timeout in ASP.net

Hi Coders,

Recently,I was asked to add session time to an existing website.

On goggling,I came across many useful links.First one from @ Geeks with Blogs
It needs that the base class must be added to each page before it is implemented.

The other one from 4guysfromrolla.com
Of course, my other useful links were there.

Finally , the solution that I found fit for my website included changes is global.aspx only.

When the user logins in successfully session variable loginname is created:
Session("Loginname") = Request("txtUser")).ToString.ToUpper 'txtUser -- my textbox on login page


And finally the code for global.aspx goes here:

Protected Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As System.EventArgs)

If TypeOf Context.Handler Is IRequiresSessionState OrElse TypeOf Context.Handler Is IReadOnlySessionState Then
Dim currentRequestpage As String = HttpContext.Current.Request.ServerVariables("SCRIPT_NAME").ToString().Substring(HttpContext.Current.Request.ServerVariables("SCRIPT_NAME").ToString().LastIndexOf("/") + 1)
If currentRequestpage.Equals("loginpage.aspx", StringComparison.CurrentCultureIgnoreCase) Then
'pages that I wanted to skip
Exit Sub
Else
If Session("Loginname") IsNot Nothing Then

Else
'redirect to login page
Response.Redirect("../loginpage.aspx?ErrMsg=3")
Response.End()
Session.Abandon()

End If
End If

End If

End Sub


The code above checks if username is nothing it redirects the User to login page.

Known issues:
If you are using a user control or alike then this function will be called multiple times.
Slowing down the speed of the website.However, in my case issue was not of much disadvantage.


In addition this code will automatically secure the website from any attacks.

KiSS (Keep It simple St***D)

Hey please let me know if you have any issues working with the code or have better ideas to share..

Regards...

Gourav

gupta.g21@gmail.com



No comments: