Click here to Skip to main content
15,884,838 members
Articles / Web Development / ASP.NET
Tip/Trick

Implementing Custom ASP.NET State Management using Redis and ASP.Net MVC5 – Part 1

Rate me:
Please Sign up or sign in to vote.
4.93/5 (7 votes)
10 Oct 2014CPOL5 min read 41.7K   17   5
A walkthrough on installing Redis server and implementing a custom ASP.NET State Management using Redis and ASP.NET MVC5.

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.

  1. 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.
  2. 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.

Image 1

Image 2

Now we have created a basic ASP.Net MVC folder with very minimal reference. The Solution explorer looks as below.

Image 3

Step2: To Download Redis server using NuGet, Right click on Solution explorer and select "Manage NuGet Packages".

Image 4

Step3: In the Search box type "Redis" and select Redis-32 and click Install. This is the Redis 32 bit server for windows platform.

Image 5

Clicking Install will download the Redis 32 bit binaries under the \packages folder as below.

Image 6

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.

Image 7

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" 
            host = "127.0.0.1" [String]
            port = "" [number]
            accessKey = "" [String]
            ssl = "false" [true|false]
            throwOnError = "true" [true|false]
            retryTimeoutInMilliseconds = "5000" [number]
            databaseId = "0" [number]
            applicationName = "" [String]
            connectionTimeoutInMilliseconds = "5000" [number]
            operationTimeoutInMilliseconds = "1000" [number]
          />
        -->
        <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.

Image 8

And System.web section in Web.config file as below.

Image 9

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.

Image 10

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.

Image 11

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.

C#
public class HomeController : Controller
    {
        //
        // GET: /Home/
        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.

Image 12

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.

Image 13

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNice Pin
Alireza_136214-Oct-17 16:33
Alireza_136214-Oct-17 16:33 
QuestionNice Pin
M Rayhan13-Oct-14 20:08
M Rayhan13-Oct-14 20:08 
Questionintresting Pin
siegeon13-Oct-14 13:02
siegeon13-Oct-14 13:02 
SuggestionRe: intresting Pin
Member 119535002-Sep-15 3:20
Member 119535002-Sep-15 3:20 
Question5* Thank you Pin
mmuekk2311-Oct-14 13:31
mmuekk2311-Oct-14 13:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.