Introduction
In Web based programming a new instance of a web page is created when a request goes to the server and returns without knowledge of prior request/pages. In order to maintain web page state across request/response ASP.Net comes with several techniques to store state date in server or client.
Cookies, Hidden fields, Query strings, View State, Control State store date in client devices and Sessions State, Application State store data in the memory of server.
ASP.NET allows saving values by using Session State utilizing the Server memory. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires.
Mainly there are two types of Session Modes in ASP.Net.
- In Proc – This is the default Session mode which uses the Web Server itself to handle Session State. This is faster than other modes, the disadvantage is that it adds extra overhead to the web server itself and it won’t save the session state data when web server recycles.
- Out Proc – This mode uses configured (in separate servers) ASP.Net State Services or SQL Server or Custom provider to store Session data. This mode will hold the session data even if the web server recycles but the data types /objects should be serializable in order to save the state.
This article I will be explaining on how to use Redis for ASP.Net Custom State Management in an ASP.Net MVC 5 application.
Before we start just a word about Redis and ASP.Net MVC;
Redis is an open source in-memory NOSQL key value data store written in ANSI C .REDIS stands for REmote DIctionary Server.
ASP.Net MVC5 is an open source web development framework from Microsoft utilizing the power of ASP.NET and the .NET Framework.
For the demo application I will be using Visual Studio Express 2013 for Web as development environment targeting .Net framework 4.5 along with Redis server for Custom ASP.Net State Management.
First I will demonstrate on how to download Redis server using NuGet.
Note: I will be configuring Redis server in the development machine itself but in real time you should configure in a different machine.
Step1: Open Visual Studio 2013 for Web and create a new ASP.Net Web application selecting Empty template and checking the option to add folders and reference for MVC as below.
Now we have created a basic ASP.Net MVC folder with very minimal reference. The Solution explorer looks as below.
Step2: To Download Redis server using NuGet, Right click on Solution explorer and select "Manage NuGet Packages".
Step3: In the Search box type "Redis" and select Redis-32 and click Install. This is the Redis 32 bit server for windows platform.
Clicking Install will download the Redis 32 bit binaries under the \packages folder as below.
Note: You are free to copy these Redis binaries to any location of your choice. Just copy everything from the Redis binaries folder to any folder and run redis-server.exe to run the server and redis-cli.exe to connect to this server through the shell.
Step4: Next we will download the ASP.NET Session State Provider for Redis as below. Right click on Solution explorer and select "Manage NuGet Packages". Type "Redis State" in the Search box and select
"RedisSessionProvider" created by Microsoft and Install.
Note: Here NuGet package manager will automatically install the dependency libraries and add the necessary configuration details into the web config file.
Step5:
Adding RedisSessionStateProvider NuGet package which will do the following:
- Add references to the ASP.NET session state provider for Redis assembly and its dependencies.
- Added the below configuration to system.web section in Web.config file.
<sessionState mode="Custom" customProvider="MySessionStateStore">
<providers>
<!---->
<add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" />
</providers>
</sessionState>
After successful installation of RedisSessionStateProvider and the dependent library,
Our Solution Explorer Reference looks as below.
And System.web section in Web.config file as below.
Note here the Redis Server is configured to local host and default port.
Now we are ready to test our MVC application to use custom Redis Session.
Step6:
First we need to start the Redis server .
Go to the \Redis_ASPNet_StateDemo\packages\Redis-32.2.6.12.1\tools directory and
Double click "redis-server.exe".
Once the server is up and running, the server will be listening on port 6379 as below.
Step7: Create a sub folder named ‘Home’ under’ \Views’ folder in our solution explorer as below.
- Solution Explorer -> Right Click Views folder -> Add -> New folder. Name the folder as ‘Home’ to keep our views.
- Solution Explorer -> Right Click Home folder -> Add -> Views... Add an empty template view and name it as Index.cshtml.
Step8: Now we need to create a corresponding controller for our Home views folder.
- Solution Explorer -> Right Click Controller folder -> Add -> Controller ... Select MVC 5 Controller – Empty template and rename the controller file as HomeController.cs.
After step 7 and step 8 our solution explorer looks as below.
Now our application is ready to run. To test hit F5 (or whatever you have configured your debug key in Visual Studio) and see the blank index page loaded.
Step9:
To test the custom Redis state management capabilities,
Add the below code to our HomeController.cs-> Index Action method .Here we are just storing data to Session variable which will be saved to Redis server.
public class HomeController : Controller
{
public ActionResult Index()
{
Session["RedisData"] = "This is stored in Redis Server , time - " + DateTime.Now.ToLongTimeString();
return View();
}
}
Next to retrieve and display the session data add the below code to Index.cshtml view.
@*@Index.cshtml*@
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Redis -ASP.NET Session State Provider </title>
</head>
<body>
<div>
<h1>Redis -ASP.NET Session State Provider </h1>
<h3> Message retrieved from Redis Session State Server : @HttpContext.Current.Session["RedisData"]</h3>
</div>
</body>
</html>
Now hit F5 (or whatever you have configured your debug key in Visual Studio) to see the Session data retrieved from Redis server.
Note: Make sure to start the Redis Server before hitting F5 as configured in web.config.
To validate the data stored in Redis server, we can use the redis-cli.exe to connect to the server. Run
redis-cli.exe and enter command "keys *" to view the data stored. Here the data will be hashed and stored to the Redis server. Optionally there are GUI client available for Redis which can be downloaded from Internet also.
Note : Please refer http://redis.io/commands for Redis shell commands.
This is just a beginner article on how to configure ASP.Net Custom State Management using Redis. To store complex data types like class objects the class should be serialized. I will update the link for Part2 of this article which will demonstrate complex data type’s storage to Redis State server once I complete the article.