1 / 27

SESSION AND COOKIE MANAGEMENT IN .NET

SESSION AND COOKIE MANAGEMENT IN .NET. Presenter, Sai Krishna. Topics Covered. 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.

xiu
Download Presentation

SESSION AND COOKIE MANAGEMENT IN .NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SESSION AND COOKIE MANAGEMENT IN .NET Presenter, Sai Krishna

  2. Topics Covered • 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

  3. Session management • 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

  4. 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")

  5. Ways of doing session management • Session management in ASP.NET can be done in two ways: Using Cookies Encoding of URLs with Session ID

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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.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>

  11. 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

  12. Cookies • 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.

  13. Creation of a cookie • 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

  14. Retrieving the cookie • 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

  15. Enter your Name            Select your interest     • VB • C# • ASP Cookie details • Hello Username. We have a new book for you: XYZ VB Book

  16. 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 "administrator@www.startvbdotnet[1].txt" and it can be found in C:\Documents and Settings\Administrator\Cookies.

  17. Problems with ASP Session State These limitations include: • Process dependent. • Server farm limitations. • Cookie dependent.

  18. Problems with user sessions in Asp • 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.

  19. Solutions 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.

  20. Improved models and solutions • 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.

  21. 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)

  22. 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.

  23. 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.

  24. 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".

  25. 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

  26. Session state element • <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"/>

  27. References • http://msdn2.microsoft.com/en-us/library/ms972429.aspx • http://www.codeproject.com/Purgatory/SessionManagementAspNet.asp • http://www.codeproject.com/aspnet/ASPNETSession.asp • http://msdn2.microsoft.com/en-us/library/h6bb9cz9(vs.71).aspx • http://www.startvbdotnet.com/aspsite/forms/cookies.aspx • http://msdn2.microsoft.com/en-us/library/ms178194.aspx

More Related