Hello everyone, I haven't written anything for more than four months. Today, let's talk about the Session storage mode in. Net v1.0/v1.1. You can search <sessionState> In MSDN 2003 to view the description of the <sessionState> node element in Web. config. There are four modes: Off, InProc, StateServer, and SQLServer. Off and InProc respectively refer to "not enabled" and "in-process storage (default value)". There are no details about these two modes, the so-called InProc is to save the Session in aspnet_wp.exe (Windows 2000 parsing ASP. NET page) or w3wp.exe (Win2003 process), once the process is terminated or reset, the Session will be lost.
I. Several causes of Session loss
Everyone who has written the code knows that Session loss is a common task. The following are the reasons why I have encountered Session loss over the past few years. I dare not say it is. The probability of Session loss is still very high. Wrong ..., It can be said to be "phase... When ..." High wow ^_^"
1. restart the computer where the Session is stored (if this is not the case, you are a fairy)
2. InProc mode: The aspnet_wp.exe or w3wp.exe processes are terminated in the "Task Manager" or other circumstances.
3. InProc mode: After the. cs file is modified, it is compiled twice (only once, sometimes not lost)
4. InProc mode: Modified Web. config
5. InProc mode, Windows 2003 Environment: Recycle application pool, restart after stopping
6. InProc mode: The. dll file in the bin directory on the server is updated.
The above lists all the reasons why the ASP. NET application reset is easy to parse in InProc mode. Do you think it is very popular? I had this feeling before, so I got used to it slowly, and then I simply didn't need this pattern. As a result, there are two attempts to use the following two modes. Now I will share them with you.
Ii. Use StateServer to save the Session
The essence of StateServer mode is to store sessions in a separate process, which is independent of aspnet_wp.exe or w3wp.exe. After this service is enabled, you can see a process named aspnet_state.exe in "Task Manager". The following describes the specific steps for setting:
1. Modify the Registry (key steps, such)
Run regedit → open the Registry → locate HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/aspnet_state/Parameters node → set the AllowRemoteConnection key value to 1 (1 is allowed, 0 indicates disabled) → set Port (Port number)
Note:
A) if ASP. NET State Service is running, you need to restart the Service after modifying the Registry content.
B) Note that the key value of the port number is stored in hexadecimal notation and can be modified in decimal format. 42424 is the default port.
C) when the key value of AllowRemoteConnection is set to "1", it means that remote computer connections are allowed. That is to say, as long as you know your service port, you can enjoy your ASP. NET State Service, that is, the Session is stored in your computer process, so please use it with caution. When the key value is "0", only stateConnectionString is "tcpip = localhost: ASP can be used only when "42424" and "tcpip = 127.0.0.1: 42424. NET State Service
2. Enable ASP. NET State Service (for example)
Right-click my computer → manage → services and applications → Services → double-click ASP. NET State Service → start (can be set to automatic ")
NOTE: If. Net Framework v1.0/v1.1 is installed, the service is available.
3. Change Web. config
Open Web. config → find the content of the <sessionState> node
<SessionState
Mode = "InProc"
StateConnectionString = "tcpip = 127.0.0.1: 42424"
SqlConnectionString = "data source = 127.0.0.1; Trusted_Connection = yes"
Cookieless = "false"
Timeout = "20"/>
→ Change it to the following content
<SessionState mode = "StateServer" stateConnectionString = "tcpip = 192.168.0.2: 42424" timeout = "20"/>
Note:
A) after being set to StateServer, the corresponding stateConnectionString must exist.
B) Note that the IP address (which can be a remote computer IP address, computer name, or domain name) and port number must be the same as the Service port of ASP. NET State Service.
3. Store the Session in SQLServer
In the SQLServer mode, the Session is stored in the SQL Server database (note that it is not Oracle, you can guess the reason by moving your toes). The following describes the specific steps for setting the Session:
1. Start related database services ()
Run SQL Server Service Manager → start SQL Server (preferably set to automatically run upon startup) → start SQL Server Agent service (preferably set to automatically run upon startup)
Note:
A) Pay attention to the startup sequence. You can also set it in the following ways: right-click my computer → manage → services and applications → Services → locate MSSQLSERVER and SQLSERVERAGENT → start and set the Startup Type to automatic"
B) the SQL Server Agent is used to clear expired sessions in the database.
2. Create a DataBase for storing sessions
Run "SQL query analyzer" → log on to the database using "sa" or a user with the db_owner permission of "master" → open the query file C:/WINNT/Microsoft. NET/Framework/v1.1.4322/InstallSqlState. SQL (stored in the Windows System directory.. Net installation directory) → directly run the SQL script → refresh the DataBase to see the DataBase named ASPState.
3. Create a user to connect to the ASPState database and authorize the user (skip this step)
The reason for this step is: first, you do not want to go to the Web. the sa password appears in config. Second, after the DataBase is started, tempdb retains the permissions of only one account in sa. All permissions of other accounts are cleared, but this DataBase is required to save the Session;
A) run SQL Server's Enterprise Manager → expand database security → right-click "login" → create "login" → enter "name" → select "SQL Server Authentication" → enter "password ""→ specify" Database "→ click" database access "→ select" ASPState "→ select" db_owner "→ click" OK "→ enter" password "Again → click" OK" then you can create a user named "SessionStateUser ", the password is "123456" for the test user)
B) run SQL Server's Enterprise Manager → expand "manage" → expand "SQL Server proxy" → right-click "job" → click "new job" → enter "name" (in this example, GrantSessionUser)) → click "Step"> New → enter "Step name" (Grant01 in this example) → select database "tempdb" → write SQL scripts "execsp_adduser 'sessionstateuser', 'sessionuser ', 'db _ owner' → OK → click "Schedule" → new → enter "name" (Start01 in this example) → select the type "Automatic startup upon SQL Server proxy startup" → OK → click "OK" to add
C). You can also run the following script to complete the preceding steps A and B at A time.
/****** Start the script ******/
-- Create a database account SessionStateUser. The default logon is ASPState.
EXEC sp_addlogin 'sessionstateuser', '123456', 'aspstatstate'
Use ASPState -- switch DataBase
-- Grant SessionStateUser the db_owner permission
Exec sp_adduser 'sessionstateuser', 'sessionuser', 'db _ owner'
Use master -- switch DataBase
BEGIN TRANSACTION
/****** Declare the variable ******/
DECLARE @ JobID BINARY (16)
DECLARE @ ReturnCode INT
SELECT @ ReturnCode = 0
-- If not, add the job category
IF (select count (*) FROM msdb. dbo. syscategories WHERE name = n' [Uncategorized (Local)] ') <1
EXECUTE msdb. dbo. sp_add_category @ name = n' [Uncategorized (Local)]'
-- Create a job www.2cto.com
EXECUTE @ ReturnCode = msdb. dbo. sp_add_job -- call the Stored Procedure sp_add_job
@ Job_id = @ JobID OUTPUT, -- assign the returned JobID to the variable
@ Job_name = n' grantsessionuser', -- job name
@ Owner_login_name = NULL, -- the default value is all
@ Description = null,
@ Category_name = n' [Uncategorized (Local)] ', -- job category attribution
@ Enabled = 1, -- enable or not
@ Policy_level_email = 0,
@ Policy_level_page = 0,
@ Policy_level_netsend = 0,
@ Policy_level_eventlog = 0,
@ Delete_level = 0
IF (@ ERROR <> 0 OR @ ReturnCode <> 0) GOTO QuitWithRollback -- rollback IF an ERROR occurs
-- Create step
EXECUTE @ ReturnCode = msdb. dbo. sp_add_jobstep -- call the Stored Procedure sp_add_jobstep
@ Job_id = @ JobID, -- input the newly created JobID
@ Step_id = 1,
@ Step_name = n'grant01 ', -- step name
@ Command = n'exec sp_adduser ''sessionstateuser'', ''sessionuser'', ''db _ owner ''',
-- SQL script to be executed (note that two consecutive single quotes are used to represent single quotes in SQL)
@ Database_name = N 'tempdb', -- DataBase used to execute the preceding SQL statement
@ Server = n '',
@ Database_user_name = n '',
@ Subsystem = n'tsql ', -- the execution type is "Transact-SQL script"
@ Cmdexec_success_code = 0,
@ Flags = 0,
@ Retry_attempts = 0,
@ Retry_interval = 1,
@ Output_file_name = n '',
@ On_success_step_id = 0,
@ On_success_action = 1,
@ On_fail_step_id = 0,
@ On_fail_action = 2
IF (@ ERROR <> 0 OR @ ReturnCode <> 0) GOTO QuitWithRollback
-- Create Scheduling
EXECUTE @ ReturnCode = msdb. dbo. sp_add_jobschedule
@ Job_id = @ JobID,
@ Name = n'start01', -- scheduling name
@ Enabled = 1,
@ Freq_type = 64 -- "64" indicates that when the SQLServerAgent service is started
IF (@ ERROR <> 0 OR @ ReturnCode <> 0) GOTO QuitWithRollback
-- Add the new job to the local database
EXECUTE @ ReturnCode = msdb. dbo. sp_add_jobserver @ job_id = @ JobID, @ server_name = n' (local )'
IF (@ ERROR <> 0 OR @ ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@ TRANCOUNT> 0) ROLLBACK TRANSACTION
EndSave:
/****** End the script ******/
4. Set Web. config content
Open Web. config → find the <sessionState> node content → modify it to the following content:
<SessionState mode = "SQLServer" sqlConnectionString = "data source = 192.168.0.2; user id = SessionStateUser; password = 123456" timeout = "20"/>
Note:
A) The initial catalog option cannot appear in sqlConnectionString.
B) the SQL Server Agent is used to clear expired sessions in the database.
C) if you skip step 3, log on to the user id using sa.
D) If sqlConnectionString is "data source = 127.0.0.1; Trusted_Connection = yes", use the local computer ASPNET (Windows 2000 system account) or Network Service (Windows 2003 system account) to log on to the database. If the database does not allow the above user to log on, an error is returned. Similarly, even if the above account can successfully log on, it must be assigned the tempdb permission on the grounds that the Session is saved in tempdb, if you do not have the access permission for this DataBase, the row will not drop.
Author Zheng wenliang