2017年10月9日 星期一

[ASP.NET] Session State modes

 ASP.NET    Session   State server   Sql server  



Introduction


ASP.NET supports the following state storage modes:

1.  InProc
2.  StateServer
3.  SQLServer
4.  Custom
5.  Off





We will learn how to set up the state modes with State server or Sql server.
In these two ways, the session variables will remain alive when web application restarts or get recycled.



Environment


Visual Studio 2017 Community
ASP.NET MVC5
.NET Framework 4.6.1




State server


Enable ASP.NET State service





WebConfig


<configuration>
<system.web>
   <sessionState mode="StateServer"
      stateConnectionString="tcpip=10.X.X.XXX:42424" cookieless="false" timeout="20"/>
/system.web>

Notice that the state server default listens on port 42424.
The port is defined in
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port.


Remote state server

If we want to use the remote server as the state service, follow the steps on the remote state machine.

1.     Change the registry’s value

Open regedit and find
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnections

Update the value to “1” and the state server will allow ALL connections from others. So make sure ONLY the ALLOWED servers can connect to it.

2.     Web farm (Optional)

For web farm, we need to generate a machine key for all web servers in web farm.

Open IIS, go to
Features ViewMachine Key






When you click
Apply, the machine key will be written into WebConfig.
For example,

<system.web>
     <machinekey validationkey="....." decryptionkey="....." validation="SHA1" decryption="AES"></machinekey>
</system.web>

 



Sql Server


Installing the Session State Database

We will install the Session State database by Aspnet_regsql.exe tool.
Open Developer Command Prompt and use the following command to enable the database.

Use current login account

$ aspnet_regsql.exe -S {SqlServerName} -E -ssadd -sstype p


Use Id/Pwd

$ aspnet_regsql.exe -S {SqlServerName} -U {ID} -P {Password} -ssadd -sstype p


Option
Description
t
Stores session data in the SQL Server tempdb database. This is the default. If you store session data in the tempdb database, the session data is lost if SQL Server is restarted.
p
Stores session data in the ASPState database instead of in the tempdb database.
c
Stores session data in a custom database. If you specify the c option, you must also include the name of the custom database using the -d option.


Update WebConfig

<configuration>
<system.web>
    <sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI;data source={server name};" />
 </system.web>
</configuration>

Or with id/pwd like following.

<sessionState mode="SQLServer" sqlConnectionString="user id={id};password={pwd}" ;data source={server name};" />



Result









Reference



沒有留言:

張貼留言