Sessions trong Traditional Load Balancing Environments
Nói chung, chúng ta dùng in-memory sessions (data stored in RAM) trong all Web Applications. Nó works well in most of the traditional hosting environments nơi chúng ta host application trong dedicated VM hoặc shared hosting plans.
Tuy nhiên, khi traffic grows, chúng ta plan for load balancing bằng cách tạo multiple Web Servers và control traffic using Load Balancers. Trong these scenarios, session wouldn't work vì requests (related to a single session) would be served by multiple servers (same server để serve requests của single session cũng possible, nhưng not suggested). Giải pháp là go for storing the sessions in a SQL Server accessible across all Web Servers của Load Balancing environment.
Sessions trong Azure auto-scale environment
Thay vì theoretical discussion trên này, hãy directly jump into some practical discussion bằng cách develop a small program that uses sessions và see how sessions work in Azure.
Hãy create a Website (bạn có thể create MVC Application as well) with the following Web Pages và deploy the application as shown in one of my previous articles,
- Azure App Service - Configure Existing Application From Visual Studio
Login.aspx
Page này chỉ accept username và password. On "Login" button click, create a session và store value của logged-in username in a session và redirect user to "Default.aspx".
Lưu ý page cũng display IPAddress "10.202.116.91" của Virtual Machine nơi web site hosted.
Default.aspx
Page này display following messages based on value in the Session.
Nếu Session có some value, thì display "Logged in user as admin. You are in 10.202.116.91" như shown in below screen capture.
Nếu session không có any value, thì display "Session is NULL. You are in 10.202.116.91" như shown in below screen capture.
Lưu ý IPAddress của Server trong cả Login.aspx và Default.aspx là same. All requests are being re-directed to the same server.
Cũng, như below screen capture, sessions are maintained using a Cookie named "ASP.NET_SessionID". This should be familiar to most of us.

Giả sử traffic đến website của chúng ta grown và chúng ta would like to scale it to two Instances. Hãy go ahead và increase the Instance count to two.
Note: Lưu ý rằng bạn cannot increase the instance count in Free and Shared tiers. Your App Service should be in "Basic", "Standard" or "Premium" tiers.

Hãy again access the Login Page và access it multiple times bằng cách refresh the page. Refreshing the page any number of times will NOT change the IPAddress.
Bạn sẽ notice that the same Web Server is serving the pages. Though we enabled scaling to two instances, the App Service is still serving the requests from one server.
Điều này might be a problem in real-world scenarios vì the same server is serving the requests even though Load Balancing is enabled và the other servers are not being utilized properly.
The reason why all the requests are being served is because of the ARR Cookie as shown below. For more information, please have a look here.

In Simple terms, cookie này has the Server information from which the initial request has been served so that all subsequent requests from the same session are served by the same VM.
Hãy disable the ARR cookie feature bằng cách navigate to the App Service's Application Settings as shown below.

Turn off the "ARR Affinity" as shown in the above screen capture và click on "Save" button to save the changes. Please restart the App Service just to clear all the sessions.
Please be a bit cautious from now onwards. The following couple of paragraphs are a bit confusing.
Important
Turning off the ARR Affinity will disable the process of creating the cookie ARRAffinity cookie. So, when the cookie is disabled, the requests might be sent to any of the available servers. So, there is no guarantee that the Sessions will be maintained properly. Sessions will work ONLY when the requests are being served from the Same server. If any of the requests are served by another server (thay vì the one where the session is stored) thì Sessions will be NULL.
Now, come back to the Web App và navigate to the Login page và notice the new IPAddress "10.202.174.84". (In your case, initially you might see the same IPAddress as before. Refreshing the page would change the IPAddress. In my case, I refreshed the page twice to get the new IPAddress as shown below.)

Clicking on the Login button will NOT guarantee that the form will be posted to 10.202.174.84. It might post the data to the other server which in my case is "10.202.116.91".
In my case, when I clicked on the "Login" button of the above screen capture, it took me to the Default page with the following values.

- IP Address is 10.202.174.84 (this is the same in my login Page).
- Session is NULL. The reason is, when login is clicked, the request might have gone to the other instance ("10.202.116.91") where my session got stored.
- Refresh the page a couple of times.
Please observe the following.
- Session has some value "admin".
- IPAddress is 10.202.116.91.
Vậy conclusion here is "Sessions" wouldn't work as expected in the Azure App Service khi bạn configure Load Balancer using the auto-scaling feature.
Here comes the savior. The Redis Cache provider. Dưới là definition from the Azure Official Web site.
Azure Redis Cache is based on the popular open-source Redis cache. It gives you access to a secure, dedicated Redis cache, managed by Microsoft và accessible from any application within Azure.
Dưới là steps required để make our sessions work as expected.
- Create the Redis Cache from the Azure Management Portal.
- Configure the Application to use the Azure Redis Cache.
- Use the Sessions.
Create the Redis Cache from the Azure Management Portal.
Hãy start creating the Redis Cache using the Azure Management Portal as shown below.
Provide the details of the Redis Cache as shown below.
Click on the "Create" button of the above screen capture. It will take a couple of minutes to create the Redis Cache.
Configure the Application to use the Azure Redis Cache
Hãy configure the application to use the Redis Cache that we have just created.
As shown in the above screen capture, go-to Package Manager Console và type the command "Install-Package StackExchange.Redis" và click "Enter".
Now, we have successfully installed the required packages. (Please note that your .NET framework should be 4 or higher.)
Để use the assemblies, we need to first added the following namespace to both our Login.aspx page and Default.aspx page.
Using StackExchange.Redis;
Hãy add a new class named "RedisConnection" to the project. Please refer the attached Project.
Để connect to Redis Cache, we need to pass the following information to the ConnectionMultiplexer.Connect function. Hãy grab them from the Portal.

- Redis Cache URL.
- Keys.
Please don't save the Keys in Code. To make things simple, I am storing the keys in the Source Code. Please refer this page which provides information on how to store the credentials.
We are now ready with the class that could be used to connect to the Redis Cache. Let's use the class to create session in the Redis Cache.
Open your Login.aspx.cs file và replace the following line of code.
Session["login"] = this.txtUsername.Text.Trim();
With.
IDatabase cache = RedisConnection.Connection.GetDatabase();
cache.StringSet("login", this.txtUsername.Text.Trim());
Open the Default.aspx.cs và replace the following line of code.
protected void Page_Load(object sender, EventArgs e) {
if (Session["login"] == null) {
Response.Write("Session is NULL. You are in " + Request.ServerVariables["LOCAL_ADDR"]);
} else {
Response.Write("Logged in user is " + Session["login"] + ". You are in " + Request.ServerVariables["LOCAL_ADDR"]);
}
}
With.
protected void Page_Load(object sender, EventArgs e) {
IDatabase cache = RedisConnection.Connection.GetDatabase();
string strLoginValue = cache.StringGet("login");
if (strLoginValue == null) {
Response.Write("Session is NULL. You are in " + Request.ServerVariables["LOCAL_ADDR"]);
} else {
Response.Write("Logged in user is " + strLoginValue + ". You are in " + Request.ServerVariables["LOCAL_ADDR"]);
}
}
Hãy deploy the code to the Azure App Service và review the changes và navigate to the Login Page as shown below.
Notice the IPAddress. It's 10.202.174.84. Now click on "Login" button. You will be taken to the Default.aspx page as shown below.
Notice that in the above screen capture, though the IPAddress is different, still we are able to see the username "admin" because the sessions are now stored in a distributed location "Redis Cache" which is accessible for both the instances.
Now, keep refreshing the page multiple times. You will notice that the IP Addresses are changing but not the value of the username.
That's it. We have learned how to store the sessions in a load Balancing Environment. You can store any kind of data in Redis Cache.
Hope you enjoyed reading the article. Your feedback is really appreciated.