


In-depth analysis of Session server configuration guide and usage experience_PHP tutorial
1. Summary
All Web programs will use Session to save data. Using an independent Session server can solve the Session sharing problem in load balancing scenarios. This article introduces the establishment of a .NET platform Several methods of Session server, and introduces various experiences and techniques when using Session.
2. About Session, SessionID and Cookies
Session The data is stored on the server side, but each client needs to save a SessionID. The SessionID is stored in Cookies and expires when the browser is closed.
The SessionID will be included in the HTTP request sent to the server. The server side will SessionID gets the session information of this user.
Many junior developers don’t know the relationship between SessionID and Cookies, so they often think that there is no connection between the two. This is incorrect. It is precisely because SessionID is stored in Cookies, so in our When saving cookies, be sure not to create SessionID objects due to the size and number of cookies. In our program, there are special treatments for SessionID cookies:
///
/// Write cookie.
///
/// string CookieName = GetType().ToString();
HttpCookie SessionCookie = null;
//Back up SessionId.
if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] ! = null)
{
string SesssionId = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value.ToString();
SessionCookie = new HttpCookie("ASP .NET_SessionId");
SessionCookie.Value = SesssionId;
} //Omit the middle code part. Only keep the logic of backing up SessionID and retrieving SessionID //If the total number of cookies exceeds 20, repeat Write ASP.NET_SessionId, in case Session is lost.
if (HttpContext.Current.Request.Cookies.Count > 20 && SessionCookie != null)
> Httpcontext.current.Response.cookies.remove ("asp.net_sessionid"); 🎜>}
}
三.搭建Session服务器的几种方式
将Session保存在独立的服务器中可以实现在多台Web服务器之间共享Session.虽然我们也可以自己开发Session存储系统, 但是使用ASP.NET自带的存储机制将更加便捷.
.NET提供了5种保存Seission的方式:
方式名称 |
存储方式 | 性能 |
Off |
设置为不使用Session功能 |
无 |
InProc |
设置为将Session存储在进程内,就是ASP中的存储方式,这是默认值。 |
性能最高 |
StateServer |
设置为将Session存储在独立的状态服务中。通常是aspnet_state.exe进程. |
性能损失10-15% |
SQLServer |
设置将Session存储在SQL Server中。 |
性能损失10-20% |
Customer |
自定制的存储方案 |
由实现方式确定 |
我们可以在Web.Config中配置程序使用的Session存储方式.默认情况下是InProc, 即保存在IIS进程中. 关于Off, InProc和Customer本文不做讲解. 相关文章大家都可以在网上搜索到.
下面主要讲解 StateServer 和 SQLServer 的应用.
四.使用 StateServer 模式搭建Session服务器
(1)服务器端配置
1.启动 Asp.net State service服务.(这个服务默认的状态为手动.修改为自动并启动.)
2.修改注册表: [HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\aspnet_state\Parameters]
设置 AllowRemoteConnection = 1 , 设置 Port = 42424 (十进制,默认即为42424)
Port是服务的端口号
AllowRemoteConnection 表示是否允许其他机器连接,0为仅能本机使用,1为可以供其他机器使用.
(2)客户端设置
在Web应用程序的Web.Config中, 我们需要修改
没有则添加(默认使用的是InProc方式)
stateConnectionString="tcpip=服务器ip:42424"
cookieless="false"
timeout="60"/>
上面的参数我们可以根据需要修改.
五.使用SqlServer模式搭建Session服务器
(1)服务器端配置
使用SqlServer模式搭建Session服务器端有两种方式. ASP.NET 1.0和1.1版本请使用方式a, 2.0即以上版本请使用方式b.
a.使用SQL文件创建Session数据库
在ASP.NET 1.0和1.1 版本中, 只能使用这种方式.对于2.0及其以上版本,请使用aspnet_regsql.exe工具.(当然此方法也通用2.0版本)
.net提供了数据库安装脚本,可以在机器的windows文件夹中找到:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ InstallSqlState.sql
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ InstallSqlStateTemplate.sql
根据ASP.NET的版本不同, 需要使用不同的SQL脚本. ASP.NET主要有1.1和2.0两个版本,可以在不同的版本文件夹找到这两个SQL.
InstallSqlState.sql 是创建默认名称的数据库"[ASPState]".此SQL可以直接运行.
InstallSqlStateTemplate.sql 可以使用自己指定的数据库保存数据.此SQL需要自己修改后运行, 打开SQL文件将其中 [DatabaseNamePlaceHolder] 替换为自己指定的数据库名称.
执行installsqlstate.sql时不需要指定数据库,可以在任意数据库上执行.此SQL会自己创建新的数据库
b. 使用aspnet_regsql.exe工具
ASP.NET 2.0版本后微软提供了aspnet_regsql.exe工具可以方便的配置Session数据库.该工具位于 Web 服务器上的"系统根目录\Microsoft.NET\Framework\版本号"文件夹中.
使用举例:
aspnet_regsql.exe -S . -U sa -P 123456 -ssadd -sstype p
-S参数:
表示数据库实例名称. 可以用"."表示本机.
-U和-P参数:
表示用户名和密码.
-E参数:
可以再-U –P 与 -E中选择一组. –E表示以当前系统用户通过windows身份验证登录数据库, -U -P则是使用SqlServer用户登录数据库.
-ssadd / –ssremove 参数:
-ssadd表示是添加Session数据库, -ssremove表示移除Session数据库.
sstype 参数:
选项 |
说明 |
t |
将会话数据存储到 SQL Server tempdb 数据库中。这是默认设置。如果将会话数据存储到 tempdb 数据库中,则在重新启动 SQL Server 时将丢失会话数据。 |
p |
将会话数据存储到 ASPState 数据库中,而不是存储到 tempdb 数据库中。 |
c |
将会话数据存储到自定义数据库中。如果指定 c 选项,则还必须使用 -d 选项包括自定义数据库的名称。 |
(2)Session client settings
This room also requires the web application to modify the
sqlConnectionString ="server=192.168.9.151; uid=sa; pwd=123456;"
/>
If a custom database name is used, you also need to formulate the allowCustomSqlDatabase attribute and add it to the database Specify the database in the connection string:
allowCustomSqlDatabase="true"
sqlConnectionString="server=192.168.9.151; DataBase=MyAspState;uid=sa; pwd=123456;"
/>
6. Summary of usage experience and skills
The following is a summary of various experiences and skills of SessionID, Session_End time, StatServer mode and SqlServer mode.
(1) StateServer mode :
1. In the web farm, please confirm that there is the same
on all web servers. 2. The objects to be saved in the Session are serializable.
3. In order to maintain session state on different web servers in the web farm, the website application path (such as LMW3SVC2) in IIS Metabase should be consistent on all servers (case sensitive).
4. ASP.NET handles Session through the HttpModuel module configured in Machine.Config. In the Config folder under the .NET installation directory, view Web.Config (version 1.1 is in Machine.Config):
SessionState.SessionStateModule"/>
... In SqlServer mode, you can enjoy the high performance and security of SqlServer. Although the storage efficiency will decrease.
6. The MachineKey of all machines needs to be the same. Configure in Machine.Config:
Copy code
The code is as follows:
/>
(2)SqlServer mode:
1. The object to be saved in the Session is serializable ized.
3. In SQLServer mode, session Expiration is done by SQL Agent using a registration task. Make sure SQL Agent is running. Otherwise, the expired Session data cannot be cleaned, which will cause the database data to keep increasing. 4. If you use SqlServer mode, the ASP.NET application path for each server in the Web farm must be the same. Synchronize the application path of the Web site in the IIS configuration database for all Web servers in the Web farm. The case must be the same because the application path to the Web site is case-sensitive.
5. The MachineKey of all machines needs to be the same. Configure in Machine.Config:
Copy the code
The code is as follows:
/>
(3)Session:
1. Sessions cannot be shared between ASP.NET and ASP directly through the Session server. Please use the solution provided by Microsoft:
http:// msdn.microsoft.com/zh-cn/library/aa479313.aspx
2. Session cannot be shared between different applications or different virtual directories of a website
3. Session expiration time is a sliding time.
4. Session stores the value type that comes with .NET for the best performance. Storing objects will reduce performance.
(4)SessionID:
1.SessionID can also be saved in the URL , just set the Cookiesless attribute of the System.Web/sessionState node in the Web.Config file:
/>
2. Generally, the SessionID remains unchanged after the Session times out or is deleted. This is because the Session ID will remain unchanged on the server after it expires. The data is cleared on the client, but the SessionID is saved on the user's browser, so as long as the browser is not closed, the SessionID in the HTTP header remains unchanged.
3. After closing the browser and accessing again, the SessionID will be different.
4. Every time an IE6 window is opened, the SessionID is different. In IE6, the Session of the two windows cannot be shared.
5. The SessionID of the FireFox tab page and the new FireFox window are the same, but the SessionID of the FF window and tab page cannot be shared. Share.
6. For pages containing FrameSet, for example:
If the suffix is .htm and the .htm file is not handed over to ASP.NET's ISAPI for processing, then based on the server speed A different SessionID is generated in each Frame page, and the same SessionID will be equal to the last SessionID after refreshing.
The solution is to change the .htm suffix to .aspx, or hand the .htm file to the ISAPI of ASP.NET for processing.
(5)Session_End event:
1. Session_End is only available in InProc mode
2. Close the browser, Session_End will not be triggered. HTTP is a stateless protocol, and the server has no way of knowing whether your browser has been closed.
3. Session_End will only be triggered when the Session expires or calls Session.Abandon. Session.Clear() only clears the data, but does not delete the session.
4. Session_End is triggered by a background thread and runs using the worker process account. Therefore, the program will not notify errors that occur.
5. Permission issues must be considered when accessing the database in Session_End. Session_End is used to run the worker process ( aspnet_wp.exe), this account can be specified in machine.config. Therefore, in Session_End, if integrity security is used to connect to SQL, it will use the worker process account identity to connect, which may cause login failure.
6. Because Session_End is initiated by an independent thread, it cannot be used in Session_End HttpContext object (Request, Response, Server and other objects are all in HttpContext), that is, methods such as Response.Redirect and Server.Transfer cannot be used.
7. Summary
I have used the SqlServer mode to implement session sharing for multiple servers in the company. Restarting the server will not cause the user reservation process to restart (booking The Session required for the process will not be lost). I hope this article will be helpful to those who build specific Session servers.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

VSCode Setup in Chinese: A Complete Guide In software development, Visual Studio Code (VSCode for short) is a commonly used integrated development environment. For developers who use Chinese, setting VSCode to the Chinese interface can improve work efficiency. This article will provide you with a complete guide, detailing how to set VSCode to a Chinese interface and providing specific code examples. Step 1: Download and install the language pack. After opening VSCode, click on the left

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

Are you getting "Unable to allow access to camera and microphone" when trying to use the app? Typically, you grant camera and microphone permissions to specific people on a need-to-provide basis. However, if you deny permission, the camera and microphone will not work and will display this error message instead. Solving this problem is very basic and you can do it in a minute or two. Fix 1 – Provide Camera, Microphone Permissions You can provide the necessary camera and microphone permissions directly in settings. Step 1 – Go to the Settings tab. Step 2 – Open the Privacy & Security panel. Step 3 – Turn on the “Camera” permission there. Step 4 – Inside, you will find a list of apps that have requested permission for your phone’s camera. Step 5 – Open the “Camera” of the specified app
