RSS

Working With Session in Asp.Net (Vb.Net Code behind)

Working With Session

- How to Check the Session expires in the main page, the redirect to the default page or login page.
- In Default.aspx page To add a label with the text “Your Name” , Text Box and Button Control with text “Go”



- To set the Session for the Name which you gave, use the following code

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If (Trim(TextBox1.Text) <> "") Then
Session("UserName") = UCase(Trim(TextBox1.Text))
Response.Redirect("Mainpage.aspx")
Else
Response.Write("User Name Required!")
End If
End Sub

To check session expires and the other pages redirect to default page
- We can check using the Query String from the other pages to the Default Page in the Page load event.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If (Request.QueryString("session") = "expired") Then
Response.Write("Your Session has Expired")
End If
End If
End Sub

To Validate the Session in other page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As 
System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If (Session.Item("UserName") <> Nothing) Then
Label1.Text = "Welcome Dear " &
Session.Item("UserName").ToString()
ElseIf (Session.IsNewSession = True) Then
Response.Redirect("Default.aspx?Session=expired")
Else
Response.Redirect("Default.aspx?Session=Empty")
End If
End If
' Response.Write("Session Time out:-" &
' *Session.Timeout.ToString())
End Sub

- To Make the Session Expiry the Session.Abandon() Method is used. This Will act like Logout.

- To Set the Session Timeout duration using the web config file’s SessionState Tag.
E.g.
<sessionState mode="InProc" timeout="10">
</sessionState>

- To Use this we can set the State to Handling the Session. Normally in a small Web Application we can use the InProc mode. Other Session Modes are StateServer,SQLServer,Off,Custom.

- The Default Session Timeout Time span is 20 minutes. We can Set the Session time out maximum of 1 year i.e, 525,601 minutes.

To Set the Session Expiry in Local IIS

- If we are using the Local IIS as web server we can set the Session expiry time through the Application Pool of the IIS.

0 comments:

Post a Comment