Turn: http://www.cnblogs.com/tonyqus/archive/2006/10/24/522618.html
1. Understand the session state Mode
Storage location
Inproc: sessionstore (aspnet_wp.exe) with active objects in the server)
StateServer: sessionis serialized and stored in a single aspnet_state.exe memory. StateServer can run on another server
Sqlserver: the session is serialized and saved in SQL Server.
Performance:
Inproc: the fastest, but the more session data, the more memory consumed on the Web server, which may affect performance.
StateServer: When storing data of basic types (such as string and integer), it is 15% slower than inproc in the same test environment. If you store a large number of objects, serialization and deserialization may affect the performance.
Sqlserver: When data of basic types (such as string and integer) is stored, it is 25% slower than inproc in the same test environment. It also has the same serialization performance problems as StateServer.
Performance tips for out-of-Proc (OOP, non-inproc) Mode
If you use the OOP mode (namely StateServer or sqlserver), serialization and deserialization objects in session state will become one of your major performance consumption. For basic types, ASP. NET completes serialization and deserialization through an internal optimization method. (Basic types include all numeric types (such as int, byte, decimal, String, datetime, timespan, guid, intptr, and uintptr ))
If you have a session variable (such as an arraylist object) and it is not a basic type, ASP. NET will use binaryformatter for serialization and deserialization, it may be relatively slow.
Therefore, for performance considerations, it is best to use the basic types listed above to store all session state data. For example, if you need to store two things, names and addresses, you can either use two string session variables in session state (method A) to store them, or (method B) create a class containing two strings to save them, and then save the class object in a session variable. For performance considerations, you should select method.
To further understand this topic, please refer to a question in the FAQ: "How serialization and deserialization work in sqlserver and StateServer Modes"
Robustness
Inproc: if the worker process (aspnet_wp.exe) is used to recycle resources or applyProgramWhen the domain (appdomain) is restarted, the session state will be lost. This is because the session state is stored in the memory space of an application domain. For configuration files (such as web. config and machine. config) or any changes to the \ bin directory (for example, a new DLL is generated after you use vs to compile the application). For more information, see kb324772. In 1.0, there is also a bug that may cause the Worker Process to restart, but this bug has been fixed in 1.1, see kb321792.
If you are using iis6.0, you can find the application pools/termination parameter in IIS manager.
For more information about application Resource Recycling, see another FAQ:
Http://www.asp.net/Forums/ShowPost.aspx? Tabindex = 1 & postid = 232621
StateServer: solves the problem of session state loss in inproc mode. Allows a webfarm to store sessions on a central server. Failure can only occur on the State server.
Sqlserver: similar to StateServer. The session state data is retained after the SQL server restarts. You can also follow the steps of kb311209 to use the SQL Server failover Cluster
Warning
Inproc: it cannot work in the Web garden format, because multiple aspnet_wp.exe instances run on the same machine. We recommend that you switch to state server or SQL Server when using web garden. Only session_end events are supported in inproc mode.
StateServer
-In Web farm, make sure that the same <machinekey> exists on all web servers. Kb313091 describes how to set it.
-Make sure that your object is serializable. For details, see kb312112.
-To maintain the session state on different Web servers in the Web farm, the path of the website application in IIS metabase (for example, \ lm \ W3SVC \ 2) it should be consistent (case sensitive) on all servers ). For details, see kb325056.
Sqlserver
-There is a bug in 1.0. If you specify integrity security in the connection string (for example, "trusted_connection = true" or "Integrated Security = sspi "), if you enable the identity simulation of Asp.net, it will not work. This problem is described in kb324479. Unfortunately, the descriptions and causes in this document are incorrect. However, a QFE fix is fixed and will be included in 1.0 SP3. This problem is fixed in 1.1.
-Make sure that your object is serializable. Otherwise, your request may be suspended. For details, see kb312112. The issue of suspension in SQL Server mode has been fixed in 1.1, and QFE fix in kb324479 has also fixed this issue. 1.0 SP3 also fixed this issue.
-To maintain the session state on different Web servers in the Web farm, the path of the website application in IIS metabase (for example, \ lm \ W3SVC \ 2) it should be consistent (case sensitive) on all servers ). For details, see kb325056.
Other resources
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/dnaspp/html/aspnetsessionstate. asp
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/dnbda/html/cachingarchch2.asp
Http://www.411asp.net/home/tutorial/specific/web/sessions
2. FAQ list
Q: The session State works on Some browsers, but not on others. Why?
Q: Why do I lose all sessions sometimes in inproc mode?
Q: The session State works on some Web servers, but does not work on other servers.
Q: Why is the session state unavailable?
Q: Why is session_end not triggered?
Q: Why is my session variable frequently lost when I use inproc mode?
Q: Why does the sessionid remain unchanged after the session times out or is deleted?
Q: Why does sessionid change every request?
Q: What is the difference between session. Abandon () and session. Clear ()?
Q: Is the timeout attribute of the session a sliding timeout value?
Q: Can I share a session between ASP. NET and ASP?
Q: Can I share the session state between Web applications (such as virtual directories or IIS applications?
Q: What types of objects can be stored in session state?
Q: Why is my request suspended after I switched to sqlserver mode?
Q: Why does response. Redirect and server. transfer not work in session_end?
Q: Can I obtain a valid httpsessionstate object and httpcontext object in session_end?
Q: How to Use session in Web service?
Q: I am writing an httphandler. Why does session STAE not work?
Q: I am using web farm and the session state will be lost whenever I redirect to another server?
Q: If cookieless is used, how can I redirect an HTTP page to an HTTPS page?
Q: Is there a lock mechanism for session state to arrange the access sequence of sessions?
Q: How can I detect a session expiration and redirect it to another page?
Q: In session_end, I tried to use SQL for some cleanup work, but failed. Why?
Q: I am using sqlserver mode. Why is my session not expired?
Q: I have a frameset page with the extension htm, and I find that each frame contained in it has a different sessionid during the first request. Why?
Q: I set enablesessionstate to readonly, but in inproc mode, I can still modify the session. Why?
Q: I set cookieless to true. After redirect, the session variable is lost. Why?
Q: What are the disadvantages of setting cookieless to true?
Q: In inproc mode, I used programming to change the Session Timeout time, which triggers session_end. Why?
Q: In sqlserver mode, can I save the session state in a database other than tempdb?
Q: How can I prevent unencrypted strings from being summarized in my connection strings?
Q: What SQL permissions do I need when I use sqlserver mode?
Q: Can I write a custom session state mode?
Q: How does serialization and deserialization work in sqlserver or StateServer mode?
Q: How can I make my state server safer?
Q: Can I subscribe to the sessionstatemodule. End event using a non-Global. asax handler?
Q: Can different applications store their session states in different databases on the same SQL server?
Q: The session State works on Some browsers, but not on others. Why?
A: It is estimated that cookieless is not used. You must ensure that your browser supports cookies. See this KB: http://support.microsoft.com/default.aspx? SCID = KB; en-US; q1_112
Q: Why do I lose all sessions sometimes in inproc mode?
A: Please refer to the robustness section of the session state mode.
Q: The session State works on some Web servers, but does not work on other servers.
A: Maybe it's a problem with the machine name, see http://support.microsoft.com/default.aspx? SCID = KB; en-US; q1_112
Q: Why is session state unavailable?
A:
-first, check the web. config, machine. config and page labels to confirm that you have enabled session state
reference:
http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconsessionstate. asp
http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpgenref/html/cpconpage. ASP
-please note that the session state is not available anywhere and anytime. It is only available in httpapplication. available after the acquirerequeststate event. For example, in global. session state is unavailable in application_onauthenticaterequest in asax
-Please confirm system. web. sessionstate. sessionstatemodule is included in the section of the configuration file. A common example is that for performance considerations, Sharepoint applications remove this module from the Web. config file, resulting in session unavailability.
Q: Why is session_end not triggered?
A: This is one of the most common problems.
1. Remember that session_end is only available in inproc Mode
2. Close the browser and session_end will not be triggered. HTTP is a stateless protocol, and the server cannot know whether your browser is closed.
3. session_end is triggered only when no operation is performed for n minutes (n = timeout value) or session. Abandon is called.
4. In case 1, session_end will be triggered by a background thread, which indicates:
In A. session_endCodeRun with a worker process account. If you access resources such as databases, you may have permission issues.
B. if an error occurs in session_end, the program will not notify you of what has happened.
5. For Case 2, session state must exist first to trigger session_end. This means that you must store some data in the session State and have completed at least one request.
6. In case 2, session_end is triggered only when the discarded session is found. In this case, if you create and discard a session in the same request, the session will not be found because it is not saved, and session_end will not be called. This is a bug in V1.0 and V1.1.
Q: Why is my session variable frequently lost when I use inproc mode?
A: It may be caused by application Resource Recycling. See the http://support.microsoft.com/default.aspx? SCID = KB; en-US; q2017148
A bug in V1.0 may cause the Worker Process to restart. It has been fixed in V1.1 and V 1.0sp2. See http://support.microsoft.com/default.aspx? SCID = KB; en-US; 321792
For more information about application Resource Recycling, see my other article: faqhttp: // www.asp.net/forums/showpost.aspx? Tabindex = 1 & postid = 232621
Q: Why does the sessionid remain unchanged after the session times out or is deleted?
A: Although the session State expires after the timeout period, the sessionid will remain until the browser session expires. That is to say, a session with the same sessionid can time out multiple times, but it always corresponds to an identical browser instance.
Q: Why does sessionid change every request?
A: If your application has never stored data in session state. In this case, a new session state (ID is also new) will be created for each request, but it will not be stored because there is no data in it.
However, two exceptions may generate the same session ID.
-If you use the same browser instance to request another page that uses the session state, the session IDs you obtain each time are the same. For details, see "Why does the sessionid remain unchanged after the session times out or is deleted ?"
-If the session_onstart event is used, Asp.net saves the session State even if the session is empty.
Q: What is the difference between session. Abandon () and session. Clear ()?
A: The main difference is that if you call session. Abandon (), session_end will be triggered (applicable only in inprocxi). In the next request, session_start will be triggered. Session. Clear () only clears data, but does not delete the session.
Q: Is the timeout attribute of the session a sliding timeout value?
A: The timeout of a session is a sliding expiration time, which means that once your page accesses the session state, the expiration time will be moved. Note: As long as the page is not disabled, the page will automatically access the session when requesting
Q: Can I share a session between ASP. NET and ASP?
A: No. But there is an articleArticleI talked about how to bypass this question: http://www.msdn.microsoft.com/library/default.asp? Url =/library/en-US/dnaspp/html/converttoaspnet. asp
Of course, there are also some third-party solutions.
Q: Can I share the session state between Web applications (such as virtual directories or IIS applications?
A: No.
Q: What types of objects can be stored in session state?
A: This is determined by the mode you use.
-If you are using the inproc mode and the object stored in the session state is a live object, you can store any object you create.
-If you are using sqlserver or State server mode, when processing a request, the object objects in session state will be serialized and deserialized, so make sure that all your objects are serializable and their classes are serializable. If no, the session State will not be stored successfully. In V1.0, there is a bug. When this problem occurs, if sqlserver mode is used, the request may be suspended without knowing it. Pending issues have been fixed in V1.1 and V1.0 SP3. The QFE fix of kb324479 also contains the fix for this problem.
For more information, see: http://support.microsoft.com/directory/article.asp? Id = KB; en-US; q312112
Q: Why is my request suspended after I switched to sqlserver mode?
A: Please refer to the question "What types of objects can be stored in session state ?" Answer
Q: Why does response. Redirect and server. transfer not work in session_end?
A: session_end is triggered inside the server. It is based on an internal timer. Therefore, when an event is triggered, it is irrelevant to any httprequest object. This is why response. Redirect and server. Transfer do not work.
Q: Can I obtain a valid httpsessionstate object and httpcontext object in session_end?
A: You can obtain the httpsessionstate object. You can use 'session' to access this object. However, you cannot access httpcontext because this event has nothing to do with the request.
Q: How to Use session in Web service?
A: You need to use some tips on the caller. You must save the cookie used by the web service. See the msdn document about httpwebclientprotocol. cookiecontainer.
Even so, if you use a proxy object to call the Web service from your page, the web service and your page cannot share the session state due to architecture restrictions.
If you call the Web service through redirect, this can be done.
Q: I am writing an httphandler. Why does session STAE not work?
A: Your httphandler interface must implement the irequiressessionstate or ireadonlysessionstate mark interface to use the session state.
Q: I am using web farm and the session state will be lost whenever I redirect to another server?
A: To maintain the session state between different servers in the Web farm, the path of the website application in IIS metabase (for example, \ lm \ W3SVC \ 2) it should be consistent (case sensitive) on all web servers ). For details, see kb325056.
Q: If cookieless is used, how can I redirect an HTTP page to an HTTPS page?
A: try the following code:
String originalurl = "/fxtest3/SUB/foo2.aspx ";
String modifiedurl = "https: // localhost" + response. applyapppathmodifier (originalurl );
Response. Redirect (modifiedurl );
Q: Is there a lock mechanism for session state to arrange the access sequence of sessions?
A: session State implements the read/write locking mechanism:
-If you have the write permission for the session State (for example, <% @ page enablesessionstate = "true" %>), the page or frame will get the write lock for this session until the request ends.
-A page or frame with the read permission on the session State (for example, <% @ page enablesessionstate = "readonly" %>) will obtain the read lock of the session until the request ends.
-Read locks block write locks. Read locks do not block read locks. Write locks block all read locks and write locks.
-This is why when two frames have Session Access Permissions at the same time, one frame must wait for the other frame to be completed first.
Q: How can I detect a session expiration and redirect it to another page?
A: This is a common problem, but unfortunately there is no simple way to complete it. We will look forward to implementing it in a major version. At the same time, if you use cookies, you can store a flag in the cookies so that you can distinguish between new browsers + new sessions and old browsers + expired sessions, the following code redirects to an expiration page when the session expires.
Void session_onstart (Object sender, eventargs e ){
Httpcontext context = httpcontext. Current;
Httpcookiecollection cookies = context. Request. Cookies;
If (Cookies ["starttime"] = NULL ){
Httpcookie cookie = new httpcookie ("starttime", datetime. Now. tostring ());
Cookie. Path = "/";
Context. response. Cookies. Add (cookie );
}
Else {
Context. response. Redirect ("expired. aspx ");
}
}
Q: In session_end, I tried to use SQL for some cleanup work, but failed. Why?
A: First, session_end is only supported in inproc mode.
Second, session_endis run by the account of the runtime worker (aspnet_wp.exe). This account can be specified in machine. config. Therefore, in your session_end, if you use integrity security to connect to SQL, it will use the identity of the Worker Process account to connect, which may cause logon failure, depending on your SQL security settings.
Q: I am using sqlserver mode. Why is my session not expired?
A: In sqlserver mode, session expiration is completed by the SQL Agent using a registration task. Check whether your SQL Agent is running.
Q: I have a frameset page with the extension htm, and I find that each frame contained in it has a different sessionid during the first request. Why?
A: The reason is that your frameset page is an HTM file instead of An ASPX page.
In general, if a frameset page is An ASPX file, When you request this page, it will first send a request to the web server, you will receive an Asp.net session cookie (where the session ID is saved), and then the browser will send a separate request for the frame, and each request will have the same session ID.
However, because your page is an HTM file, the first request will not obtain any session cookie, because the page is processed by ASP rather than Asp.net, then, the browser sends a separate request for each frame. However, each separate request will not hold any session ID, so that each frame will create its own session. This is why the session IDs you see in each frame are different. The last request will win because it will overwrite the cookie written by the first two requests. If you refresh it once, you will see that they have the same session ID.
This behavior is determined by the design. The simple solution is to rename the frameset page as Aspx.
Q: I set enablesessionstate to readonly, but in inproc mode, I can still modify the session. Why?
A: even if the enablesessionstate is set to readonly, you can modify the session in inproc mode. The only difference is that the session will not be locked in the request, which is determined by the design. I am sorry for not mentioning this in msdn.
Q: I set cookieless to true. After redirect, the session variable is lost. Why?
A: If you are using cookieless, you must use a relative path (such as .. \ hello. aspx) instead of an absolute path (such as \ Foo \ bar \ hello. aspx ). If you are using an absolute path, ASP. NET will not save the session ID in the URL.
Q: What are the disadvantages of setting cookieless to true?
A: cookieless = true indicates some potential rules, mainly including:
1. You cannot use absolute paths on your page
2. You must perform some additional actions to switch between HTTP and HTTPS.
3. If your customer sends a link to a friend, the URL will contain the session ID. The two users can use the same session ID at the same time.
Q: In inproc mode, I used programming to change the Session Timeout time, which triggers session_end. Why?
A: This is a bug in inproc. If you change the Session Timeout value to another value, session_end will be called (but session_start will not be called ). We hope to fix this error in V2.0.
Q: In sqlserver mode, can I save the session state in a database other than tempdb?
A: Yes. See kb311209.
Q: How can I prevent unencrypted strings from being summarized in my connection strings?
A: see SQL trusted connection or save the connection string in the Registry as encrypted data. For more information, see kb329250 and kb329290.
Q: What SQL permissions do I need when I use sqlserver mode?
A: The caller must have the exec permission for the following stored procedures,
DBO. tempgetappid
DBO. tempgetstateitem
DBO. tempgetstateitemexclusive
DBO. tempreleasestateitemexclusive
DBO. tempinsertstateitemlong
DBO. tempinsertstateitemshort
DBO. tempupdatestateitemlong
DBO. tempupdatestateitemshort
DBO. tempupdatestateitemshortnulllong
DBO. tempupdatestateitemlongnullshort
DBO. tempremovestateitem
DBO. tempresettimeout
In V1.1, you also need to have the exec permission for the following stored procedure
DBO. tempgetstateitem2
DBO. tempgetstateitemexclusive2
Note that the owner of the stored procedure must have select/insert/update/delete permissions on the session state table (DBO. aspstatetempsessions and DBO. aspstatetempapplications. Generally, the owner is the account that executes installsqlstate. SQL (or the persistent version, see kb311209) to install the tables, stored procedures, and databases required by the SQL session state.
Note that if your session state table is in tempdb (by default) And you recycle SQL Server resources, all permission settings on this table will be lost.
Q: Can I write a custom session state mode?
A: (to be translated)
Q: How does serialization and deserialization work in sqlserver or StateServer mode?
A: (to be translated)
Q: How can I make my state server safer?
A: If the State server and web server run on one machine, set the DWORD item of HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ aspnet_state \ Param ters \ allowremoteconnection to 0, this allows the State server to run locally only. This prevents remote clients from accessing the State server. This feature is available in V1.1 and also available in V1.0 SP3.
The State server must be protected by the firewall to prevent external connections to ensure real security. The default port is TCP 42424. You can set HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ aspnet_state \ Param ters \ port to change it. In local mode, all external connections except 127.0.0.1 are blocked; in remote mode, all addresses are explicitly disabled, except for connections to the WEV server.
Using IPSec is another way to protect the State server.
Q: Can I subscribe to the sessionstatemodule. End event using a non-Global. asax handler?
A: the answer is no. When sessionstatemodule triggers the end event, only the methods defined in global. asax are triggered.
This is for security reasons. Assume that Asp.net allows users to use other processing programs to process end events. In this case, users usually use a page method as the processing program. When you pass in the processing program during event subscription, the processing program will be associated with the httpapplication instance where your program runs. Please note that the httpapplication instance will be recycled to process other requests. In this way, when the end event is triggered, Asp.net will call the processing program, and the associated httpapplication instance has been used by another request, which will lead to various problems. To avoid this risk, V1.0 decides to call the method defined in global. asax. I hope you can all accept this restriction.
Q: Can different applications store their session states in different databases on the same SQL server?
A: the answer is yes. See: http://support.microsoft.com/default.aspx? SCID = KB; en-US; 836680