how session and cookies are managed in asp.net

27

Upload: apextgi

Post on 18-Jul-2016

16 views

Category:

Documents


3 download

DESCRIPTION

A session is defined as the period of time that a unique user interacts with a Web application.Pro-grammatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session

TRANSCRIPT

Page 2: How Session and Cookies are Managed in ASP.net

Introduction to session management Ways of doing session management Creating and Handling cookies Problems with User sessions Improved models and solutions Session state element References

Page 3: How Session and Cookies are Managed in ASP.net

A session is defined as the period of time that a unique user interacts with a Web application.

Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session

Page 4: How Session and Cookies are Managed in ASP.net

Session("Stocks") = "MSFT; VRSN; GE" On subsequent pages these values are read and the

Web application has access to these values without the user re-entering them:

' Get Stocks, split string, etc. Dim StockString StockString = Session("Stocks")

Page 5: How Session and Cookies are Managed in ASP.net

Session management in ASP.NET can be done in two ways:

Using Cookies

Encoding of URLs with Session ID

Page 6: How Session and Cookies are Managed in ASP.net

Cookie-based Session Handling To enable cookie-based session handling, make sure that

web.config file of the web-application contains the following entry: <sessionState mode="InProc" cookieless="false" timeout="20" /> Let’s say the browser makes a request to a server. This is the first request from the browser to the server. For e.g. for a request: http://localhost/WebApplication1/WebForm1.aspx The HTTP request header sent by the browser would be as shown below:1. GET /WebApplication1/WebForm1.aspx HTTP/1.1 2. Accept: image/gif, image/x- xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-excel, application/vnd.ms- powerpoint, application/ msword, application/x-shockwave-flash, */* 3. Accept-Language: en-us 4. Accept-Encoding: gzip, deflate 5. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com]; .NET CLR 1.1.4322) 6. Host: localhost 7. Connection: Keep-Alive

Page 7: How Session and Cookies are Managed in ASP.net

The response send back by the server would consist of a HTTP response header and response body. The response header would look something like this:1. HTTP/1.1 200 OK 2. Server: Microsoft-IIS/5.0 3. Date: Wed, 07 Jan 2004 09:31:07 GMT 4. X-Powered-By: ASP.NET 5. X- AspNet-Version: 1.1.4322 6. Set- Cookie: ASP.NET_SessionId=ll345q550ozqll45qithgi45; path=/ 7. Cache-Control: private 8. Content-Type: text/html; charset=utf-8 Content-Length: 540

Page 8: How Session and Cookies are Managed in ASP.net

If the browser clicks on a button of the first page to make a request to WebForm2.aspx, the request header sent would be:

GET /WebApplication1/WebForm2.aspx HTTP/1.1 Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com]; .NET CLR 1.1.4322) Host: localhost Connection: Keep-Alive Cookie: ASP.NET_SessionId= ll345q550ozqll45qithgi45

Page 9: How Session and Cookies are Managed in ASP.net

For cookie-less Session handling we need to set the ‘cookieless’ attribute to ‘true’ in web.config.<sessionState mode="InProc" cookieless="true" timeout="20" /> The request header is as shown below. (Similar to earlier request header in cookie-based session handling)1. GET /WebApplication1/WebForm1.aspx HTTP/1.1 2. Accept: image/gif, image/x- xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-excel, application/vnd.ms- powerpoint, application/ msword, application/x-shockwave-flash, */* 3. Accept-Language: en-us 4. Accept-Encoding: gzip, deflate 5. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com]; .NET CLR 1.1.4322) 6. Host: localhost 7. Connection: Keep-Alive

Page 10: How Session and Cookies are Managed in ASP.net

The response returned by the browser is as followsHTTP/1.1 302 Found

Server: Microsoft-IIS/5.0

Date: Wed, 07 Jan 2004 10:25:25 GMT

X-Powered-By: ASP.NET

X- AspNet-Version: 1.1.4322

Location:/WebApplication1/(bcgmybvma1y45czof4me3sq4)/WebForm1.aspx

Cache-Control: private

Content-Type: text/html; charset=utf-8

Content-Length: 174

<html><head><title>Object moved</title></head><body> <h2>Object moved to

<a href='/WebApplication1/(bcgmybvma1y45czof4me3sq4)/WebForm1.aspx'>here</a>.</h2> </body></html>

Page 11: How Session and Cookies are Managed in ASP.net

The Request header it sends would be as shown below:

GET /WebApplication1/(bcgmybvma1y45czof4me3sq4)/WebForm1.aspx HTTP/1.1

Accept: image/gif, image/x- xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-excel, application/vnd.ms- powerpoint, application/ msword, application/x-shockwave-flash, */*

Accept-Language: en-us

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com]; .NET CLR 1.1.4322)

Host: localhost

Connection: Keep-Alive

Page 12: How Session and Cookies are Managed in ASP.net

A Cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings.

The most common use of a cookie is to store information about the user and preferences the user makes.

Page 13: How Session and Cookies are Managed in ASP.net

The System.Web namespace offers a class called HttpCookie to create cookies. Private Sub Select_Click(By Val sender As System.Object, By Val e As_System.EventArgs) Handles Select.ClickDim newCookie As HttpCookie = New HttpCookie("Books")newCookie.Values.Add("Name", TextBox1.Text)newCookie.Values.Add("FavBook", RadioButtonList1.SelectedItem.Text)newCookie.Expires = #12/31/2008#Response.Cookies.Add(newCookie)Label3.Text = "Cookie Created"Select.Visible = FalseTextBox1.Visible = FalseLabel1.Visible = FalseLabel2.Visible = FalseRadioButtonList1.Visible = FalseEnd Sub

Page 14: How Session and Cookies are Managed in ASP.net

Private Sub Retrieve_Click(By Val sender As System.Object, By Val e As_System.EventArgs) Handles Retrieve.ClickLabel3.visible=False Label4.Text = "Hello" &" "& Request.Cookies("Books")("Name") & "."&_"We have a new book for you:"If Request.Cookies("Books")("FavBook") = "VB" ThenLabel5.text="XYZ VB Book"ElseIf Request.Cookies("Books")("FavBook") = "C#" ThenLabel5.text="ABC C# Book"ElseLabel5.text="Startvbdotnet.com's ASP Book"End IfEnd Sub

Page 15: How Session and Cookies are Managed in ASP.net

Enter your Name            Select your interest     VB C# ASP  

Cookie details Hello Username. We have a new book for

you: XYZ VB Book

Page 16: How Session and Cookies are Managed in ASP.net

HttpCookie aCookie = new HttpCookie("Mycookie");

aCookie.Values["userName"] = “user name"; aCookie.Values["lastVisit"] =

DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(aCookie);

The cookie that will be created with the code will be in the form of "[email protected][1].txt" and it can be found in C:\Documents and Settings\Administrator\Cookies.

Page 17: How Session and Cookies are Managed in ASP.net

These limitations include: Process dependent. Server farm limitations. Cookie dependent.

Page 18: How Session and Cookies are Managed in ASP.net

The stateless nature of HTTP makes the inclusion of a mechanism to save application state between user requests a must—the server must be able to identify the same user across multiple requests.

First, the 120-bit session ID used to identify the session is always stored as a cookie on the browser. So, if the security policy of a user's employer disallows cookies, the Session object cannot be populated.

Second, the data associated with the session and accessed through the session ID is stored on the Web server that processed the initial request and started the session. As a result, the session data can’t be shared in a web farm scenario where multiple web servers are processing requests from multiple clients.

Page 19: How Session and Cookies are Managed in ASP.net

ASP.NET session state solves all of the above problems associated with classic ASP session state:

Process independent Support for server farm configurations. Cookie independent.

Page 20: How Session and Cookies are Managed in ASP.net

The ASP.NET session implementation addresses both of these weaknesses by allowing for "cookieless" sessions and off-server storage of session data. The ASP.NET session state module is configured declaratively in the Web.config file like so:<sessionState mode="InProc" cookieless="false" timeout="20" /> In this case, the mode attribute is set to InProc (the default) to indicate that the session state is stored in memory by ASP.NET and that cookies will not be used to pass the session ID. Instead, the session ID is inserted into the query string for a page’s URL.

Page 21: How Session and Cookies are Managed in ASP.net

For example, using InProc mode, after a session is established, a call to a hypothetical ASP.NET page would look something like the following:

http://my.website.com/(55mfgh55vgblurtywsityvjq)/education.aspx

ASP.NET offers three session management solutions. They are:

InProcess, StateServer (outProcess), SQLServer (database based)

Page 22: How Session and Cookies are Managed in ASP.net

InProc:This is same as the conventional ASP session management. Session is stored in memory on the web server.

StateServer session managementBy setting the mode attribute to StateServer, is storing session data in a separate in-memory cache controlled by a Windows service running on a separate machine. The state service, called the ASP.NET State Service (aspnet_state.exe), is configured by the stateConnectionString attribute in the Web.config file.It specifies the service’s server and the port it monitors:<sessionState mode="StateServer" stateConnectionString="tcpip=myserver:42424" cookieless="false" timeout="20" />using the state service has the advantages of process isolation and sharability across a web farm.

Page 23: How Session and Cookies are Managed in ASP.net

Session management with SQL ServerIn this case, ASP.NET attempts to store session data on the SQL Server specified by a sqlConnectionString attribute that would contain the data source and security credentials necessary to log on to the server. To configure the SQL Server with the appropriate database objects, an administrator would also need to create the ASPState database by running the InstallState.sql script found in the WinDir\ Microsoft.Net\Framework\Version folder (where WinDir is the name of your server’s Windows folder and Version is the installation folder for the appropriate version of the .NET Framework you’re using).

osql –S localhost –U sa –P –i Installsqlstate.sql ( cmd prompt)<sessionState mode="SqlServer" sqlConnectionString="data source=127.0.0.1;user id= sa; password=" cookieless="false" timeout="20" /> Once the SQL Server is configured, the application code should run identically to the InProc mode.

By storing session state in the database, you’re effectively trading performance for scalability and reliability.

Page 24: How Session and Cookies are Managed in ASP.net

To use StateServer mode Make sure ASP.NET state service is running on the remote server

that will store session state information. This service is installed with ASP.NET and is located by default at <Drive>:\systemroot\Microsoft.NET\Framework\version\aspnet_state.exe.

In the application's Web.config file, set mode=StateServer and set the stateConnectionString attribute. For example, stateConnectionString="tcpip=dataserver:42424".

To use SQLServer mode Run InstallSqlState.sql (installed by default in

<Drive>:\systemroot\Microsoft.NET\Framework\version) on the computer running SQL Server that will store the session state. This creates a database called ASPState with new stored procedures and ASPStateTempApplications and ASPStateTempSessions tables in the TempDB database.

In the application's Web.config file, set mode=SQLServer and set the sqlConnectionString attribute. For example, sqlConnectionString="data source=localhost; Integrated Security=SSPI; Initial Catalog= northwind".

Page 25: How Session and Cookies are Managed in ASP.net

InProc - stored in memory on web server This is the default setting. Pros: least overhead, fastest performance Cons: breaks web clusters, restarting IIS loses

sessions StateServer - managed by a remote service

(aspnet_state) HTTP protocol over TCP port. Pros: reasonably fast, works with clusters Cons: clear text, no authentication, overflows...

SQLServer - stored in SQL Server DB tables Uses normal ODBC connection. Pros: reliable, scalable Cons: relatively slow, much overhead

Page 26: How Session and Cookies are Managed in ASP.net

<sessionState mode="Off|InProc|StateServer|SQLServer" cookieless="true|false" timeout="number of minutes" stateConnectionString="tcpip= server:port" sqlConnectionString="sql connection string" stateNetworkTimeout="number of seconds"/>

Page 27: How Session and Cookies are Managed in ASP.net