Download SESSION AND COOKIE MANAGEMENT IN .NET

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

URL redirection wikipedia , lookup

Transcript
Presenter,
Sai Krishna







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

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
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")


Session management in ASP.NET can be done in
two ways:
Using Cookies
Encoding of URLs with Session ID
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

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 ContentLength: 540

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

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

The response returned by the browser is as follows
HTTP/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.asp
x
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'>h
ere</a>.</h2> </body></html>

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.mspowerpoint, application/ msword, application/x-shockwaveflash, */*
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

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.

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.Click
Dim 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 = False
TextBox1.Visible = False
Label1.Visible = False
Label2.Visible = False
RadioButtonList1.Visible = False
End Sub

Private Sub Retrieve_Click(By Val sender As System.Object,
By Val e As_
System.EventArgs) Handles Retrieve.Click
Label3.visible=False
Label4.Text = "Hello" &" "&
Request.Cookies("Books")("Name") & "."&_
"We have a new book for you:"
If Request.Cookies("Books")("FavBook") = "VB" Then
Label5.text="XYZ VB Book"
ElseIf Request.Cookies("Books")("FavBook") = "C#" Then
Label5.text="ABC C# Book"
Else
Label5.text="Startvbdotnet.com's ASP Book"
End If
End Sub
Enter your Name
Select your interest
 VB
 C#
 ASP


Cookie details
Hello Username. We have a new book for
you: XYZ VB Book


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.



These limitations include:
Process dependent.
Server farm limitations.
Cookie dependent.



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.



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.

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.




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)


InProc:
This is same as the conventional ASP session
management. Session is stored in memory on the web
server.
StateServer session management
By 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.


Session management with SQL Server
In 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.

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_s
tate.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".


InProc - stored in memory on web server This
is the default setting.



StateServer - managed by a remote service
(aspnet_state) HTTP protocol over TCP port.



Pros: least overhead, fastest performance
Cons: breaks web clusters, restarting IIS loses
sessions
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

<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"/>






http://msdn2.microsoft.com/enus/library/ms972429.aspx
http://www.codeproject.com/Purgatory/SessionManage
mentAspNet.asp
http://www.codeproject.com/aspnet/ASPNETSession.as
p
http://msdn2.microsoft.com/enus/library/h6bb9cz9(vs.71).aspx
http://www.startvbdotnet.com/aspsite/forms/cookies.asp
x
http://msdn2.microsoft.com/enus/library/ms178194.aspx