ASP. NET session FAQ

Source: Internet
Author: User
Tags what sql metabase
ASP. NET session FAQ

By Patrick Y. NG
Address: http://forums.asp.net/7504/ShowPost.aspx
Translator: Tony Qu (from blueprint Translation Team)

This article is divided into two parts:
1. "Understanding session state mode"-helps you understand three sessions
State difference
2. FAQ

1. Understand 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:
Session is serialized and stored 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), session
Serialization and deserialization objects in 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 sessions
State data. For example, if you need to store two things, the name and the address, you can use two strings in session state (method)
You can also create a class containing two strings (method B) to save the class objects 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 (aspnet_wp.exe) recycles resources or restarts the application domain (appdomain), the session
State will be lost. This is because 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
Application found in Manager
Pools/termination.

For more information about application Resource Recycling, see another FAQ:
Http://www.asp.net/Forums/ShowPost.aspx? Tabindex = 1 & postid = 232621

StateServer: solved the inproc mode session
State loss. Allows a webfarm to store sessions on a central server. Only in the state
Server.

Sqlserver: similar to StateServer. Session state data is stored in SQL
After the server is restarted, it is retained. You can also follow the steps of kb311209 to use the SQL Server failover Cluster

Warning
Inproc: it cannot be in the Web
Garden, because in this mode, multiple aspnet_wp.exe instances run on the same machine. We recommend that you use web garden to switch to state.
Or SQL Server. Only session_end events are supported in inproc mode.

StateServer
-In the Web
In 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 session state, IIS
The website application paths (such as/lm/w3svc/2) in metabase 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 (such as "trusted_connection = true" or
"Integrated
Security = sspi "), and 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, there is already a QFE
The 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, QFE of kb324479
Fix also fixes this issue. 1.0 SP3 also fixed this issue.
-To maintain session state, IIS
The website application paths (such as/lm/w3svc/2) in metabase 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:
In inproc mode, why do I lose all sessions sometimes?
Q: 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: I can share sessions between Web applications (such as virtual directories or IIS applications ).
State?
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:
In session_end, can I obtain a valid httpsessionstate object and httpcontext object?
Q: On the web
How to Use session in service?
Q: I am writing an httphandler. Why does session STAE not work?
Q: I am using Web
Farm, And when I redirect to another server, the session state will be lost?
Q:
If cookieless is used, how can I redirect an HTTP page to an HTTPS page?
Q: Session
Does the State have a locking mechanism 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 In 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 by myself?
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: different applications can set their sessions
Is the State stored in different databases on the same SQL server?

Q:
Session state works on Some browsers, but not on others. Why?
A:
It is estimated that you have not used cookieless. 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: 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 the session
State unavailable?
A:
-First, check the Web. config, Machine. config, and page labels to confirm that you have enabled the session.
State
References:
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

-Pay attention to session
State is not available anywhere and anytime. It is only available after the httpapplication. acquirerequeststate event. For example
Session state is unavailable in application_onauthenticaterequest in global. asax.
-
Make sure that the system. Web. sessionstate. sessionstatemodule is included in the configuration file <
Httpmodules>. 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 or session. Abandon is called for n minutes (n = timeout value ).
4.
In Case 1, session_end will be triggered by a background thread, which indicates:
A.
The code in session_end runs with the worker process account. If you access resources such as databases, permission issues may occur.
B.
If an error occurs in session_end, the program will not notify you of what has happened.
5. For Case 2, to trigger session_end, the session
State must exist first. 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
Session, because the session is not saved, it will not be found 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:
Could be caused by application Resource Recycling, see 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
When the State expires, sessionid will remain until the browser session expires. That is to say, a session with the same sessionid can time out multiple times, but always corresponds to the same 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 will be created for each request.
State (ID is also new), 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 using session state
The IDS 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 article 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:
I can share sessions between Web applications (such as virtual directories or IIS applications ).
State?
A: No.

Q: In the session
What types of objects can be stored in state?

A: This is determined by the mode you use.
-If you are using the inproc mode
Objects in state are live objects, so you can store any objects you create.
-If you are using sqlserver or state
Server mode. when processing a request, the session
Object objects in state will be serialized and deserialized, so make sure that your objects are serializable and their classes are all serializable. If no, 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 in V1.1 and V1.0
SP3 has been fixed. 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 "in session
What types of objects can be stored in the 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 does not work.

Q:
In session_end, can I obtain a valid httpsessionstate object and httpcontext object?

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 flag interface irequiressessionstate or ireadonlysessionstate TO USE THE SESSION
State.

Q: I am using web farm, and every time I redirect to another server, the session
Will the State be lost?
A: To maintain the session state between different servers in the Web farm, IIS
The path of the website application in metabase (for example,/lm/w3svc/2) 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: Session
Does the State have a locking mechanism to arrange the access sequence of sessions?
A: session State implements the read/write locking mechanism:
-Session
State has write permission (for example, <% @ page enablesessionstate = "true" %>
The page or frame will get the write lock of this session until the request ends.
-Read the session State (for example, <% @ page)
The enablesessionstate = "readonly" %>) page or frame will get the read lock for this session until the request ends.
-
Read locks block write locks. Read locks do not block read locks. Write locks block all read and write locks.
-
This is also 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 accomplish 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 connects to SQL, which will be connected using the identity of the Worker Process account, 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 performed by SQL
The agent is completed 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 In 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, a request will first be sent to the Web server, and you will receive an Asp.net session
Cookie (where the session ID is saved). Then, the browser sends a separate request to the frame, and each request will have the same session ID.

However, because your page is an HTM file, the first request will not get any session
Cookie, because the page is processed by ASP rather than Asp.net, then the browser will send a separate request for each frame. However, this time each separate request will not hold any session
Id. In this way, each frame creates its own session. This is why the session you see in each frame
Different IDs. 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:
Although 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 relative paths (such as ../Hello. aspx) instead of absolute paths (such as/Foo/BAR/Hello. aspx ). If you are using an absolute path, ASP. NET does not set the session
The ID is saved 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 client sends a link to a friend, the URL will contain the session ID, and 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, I can set the session
Is the State stored in databases 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.
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 pair the session state table (DBO. aspstatetempsessions and
DBO. aspstatetempapplications) with select/insert/update/delete
Permission. Generally, the owner is the account that executes installsqlstate. SQL (or the persistent version, see kb311209) to install the SQL session.
Tables, stored procedures, and databases required by state

Note that if your session state table is in tempdb (by default ),
The server recycles resources. All permission settings on this table will be lost.

Q: I can write custom sessions by myself.
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
Is server safer?
A: If the State server and Web
Server runs on a machine by setting HKEY_LOCAL_MACHINE/system/CurrentControlSet/services/
The DWORD of aspnet_state/Param ters/allowremoteconnection is 0.
Server only runs locally. 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 is recycled to process other requests. In this way, when the end event is triggered, Asp.net will call the handler and
The httpapplication instance has been used by another request, which may cause various problems. In order to avoid this risk, the call is decided in V1.0.
The method defined in global. asax. I hope you can all accept this restriction.

Q: different applications can save their session state in the same SQL
In different databases on the server?
A: the answer is yes. See: http://support.microsoft.com/default.aspx? SCID = KB; en-US; 836680

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.