Five Best Ways To Use Redis With ASP.NET MVC

In this article, we are going to focus on the best 5 ways we can use Redis cache to increase the performance of the application.

If you are new to Redis Cache on Windows, just go through the “Installing Redis Cache on Windows” article first to get a basic idea of what Redis Cache is and how to install it on a Windows machine.

Note - The same example can be used with Redis Cache on Linux. We do not require any change; just use the port and host of Redis stored on the Linux machine by default. That’s it.

We develop various web applications nowadays, keeping the performance of the application in mind. For achieving performance, we apply normal forms to the database, index the tables, and we also try to split the database into two parts - one for transactional usage and another one for reporting. On the web application server end, we try to add logic to spin machines as the utilization of the server grows, along with adding the load balancer on top to split the user requests. Sessions management is also done to check the code for proper disposal of objects. 

Use Redis With ASP.NET MVC 

Topics we will cover here

  1. Counter
  2. Binding Dropdown
  3. Multistep Forms
  4. Cache Charts data.
  5. Session Provider.

We are going to look at the whole example and understand the source code so that we can start using it today with our projects. You can download the complete Source Code here.

Download free Redis Client to view the data from Redis.

  1. RedisReact-winforms (Free)
    https://github.com/ServiceStackApps/RedisReact

  2. Keylord (14 Days Trial)
    https://protonail.com/keylord/download

  3. Fastoredis (Free)
    https://fastoredis.com/

Creating Project

Let’s start with creating a project in Visual Studio 2015.

Use Redis With ASP.NET MVC 

After creating a project, we are going to add a NuGet package to access Redis from an ASP.NET application.

Adding NuGet Package

We are going to install the following.

  1. ServiceStack.Redis package.

    Use Redis With ASP.NET MVC

After we install this package, we are going to see how to use a counter.

Counter

Counter means an incrementor of values. For doing that in Redis, we have a readymade command.

“INCRBY key increment” 

If you want to try this with Redis client, you can type the similar command. Just ensure that your Redis Server is running before using this command.

Use Redis With ASP.NET MVC  

In WebRedis application which we have created, we are going to add a controller with the name “Counter”.

Code Snippet

 

  • In this part, we have added a controller with name Counter and an action method with the same name.
  • Next, inside the action method, we are getting the default host of Redis “localhost” which we have stored in the appsettings file, the same way we stored port “6379”.
  • Next, let us create a connection by creating an instance of RedisEndPoint and passing the host and port to it.
  • After that, we pass the endpoint connection to Redis client and inside that, we call the increment method and pass 2 parameters - 1. “key” 2. Amount (the value it should be increment by). We have kept “1”.
  • To display on View, we are assigning a value to ViewBag.

 

  1. using System;  
  2. using System.Configuration;  
  3. using System.Web.Mvc;  
  4. using ServiceStack.Redis;  
  5.   
  6. namespace WebRedis.Controllers  
  7. {  
  8.     public class CounterController : Controller  
  9.     {  
  10.         // GET: Counter  
  11.         public ActionResult Counter()  
  12.         {  
  13.             var host = ConfigurationManager.AppSettings["host"].ToString();  
  14.             var port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);  
  15.             RedisEndpoint redisEndpoint = new RedisEndpoint(host, port);  
  16.   
  17.             using (var client = new RedisClient(redisEndpoint))  
  18.             {  
  19.                 ViewBag.Visit = client.Increment("Website_Counter", 1);  
  20.             }  
  21.               
  22.             return View();  
  23.         }  
  24.     }  
  25. }  

On the View, we are just going to display this value.

  1. @{  
  2.     ViewBag.Title = "Counter";  
  3. }  
  4.   
  5. <h2>Counter</h2>  

Visit:- @ViewBag.Visit

Output

Use Redis With ASP.NET MVC  

Data Stored in Redis Cache

Use Redis With ASP.NET MVC  

After having a View on Counter, next, we are going to see how we can load the drop-down values from Redis Cache.

Binding Dropdown

In this part, we are going to get the cache values of the drop-down list. On the first request, we pull the values from the database and add these to Redis Cache and on the next request, we are not going to hit the database but our Redis Cache.

For doing that, we are going to add a new controller with name “DemoDropdown” and we are going to bind 2 drop-down lists - the first one is Country and another one is State.

For storing a collection of data and retrieving, I have written a centralized class with name “CacheStrigsStack”. This class creates a connection and has all the methods to store the list and retrieve values from Redis.

Code Snippet

  1. public class CacheStrigsStack  
  2.     {  
  3.         private readonly RedisEndpoint _redisEndpoint;  
  4.         public CacheStrigsStack()  
  5.         {  
  6.             var host = ConfigurationManager.AppSettings["host"].ToString();  
  7.             var port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);  
  8.             _redisEndpoint = new RedisEndpoint(host, port);  
  9.         }  
  10.   
  11.         public bool IsKeyExists(string key)  
  12.         {  
  13.             using (var redisClient = new RedisClient(_redisEndpoint))  
  14.             {  
  15.                 if (redisClient.ContainsKey(key))  
  16.                 {  
  17.                     return true;  
  18.                 }  
  19.                 else  
  20.                 {  
  21.                     return false;  
  22.                 }  
  23.             }  
  24.         }  
  25.   
  26.         public void SetStrings(string key, string value)  
  27.         {  
  28.             using (var redisClient = new RedisClient(_redisEndpoint))  
  29.             {  
  30.                 redisClient.SetValue(key, value);  
  31.             }  
  32.         }  
  33.   
  34.         public string GetStrings(string key, string value)  
  35.         {  
  36.             using (var redisClient = new RedisClient(_redisEndpoint))  
  37.             {  
  38.                 return redisClient.GetValue(key);  
  39.             }  
  40.         }  
  41.   
  42.         public bool StoreList<T>(string key, T value, TimeSpan timeout)  
  43.         {  
  44.             try  
  45.             {  
  46.                 using (var redisClient = new RedisClient(_redisEndpoint))  
  47.                 {  
  48.                     redisClient.As<T>().SetValue(key, value, timeout);  
  49.                 }  
  50.                 return true;  
  51.             }  
  52.             catch (Exception)  
  53.             {  
  54.                 throw;  
  55.             }  
  56.         }  
  57.   
  58.         public T GetList<T>(string key)  
  59.         {  
  60.             T result;  
  61.   
  62.             using (var client = new RedisClient(_redisEndpoint))  
  63.             {  
  64.                 var wrapper = client.As<T>();  
  65.   
  66.                 result = wrapper.GetValue(key);  
  67.             }  
  68.   
  69.             return result;  
  70.         }  
  71.   
  72.         public long Increment(string key)  
  73.         {  
  74.             using (var client = new RedisClient(_redisEndpoint))  
  75.             {  
  76.                 return client.Increment(key, 1);  
  77.             }  
  78.         }  
  79.   
  80.         public long Decrement(string key)  
  81.         {  
  82.             using (var client = new RedisClient(_redisEndpoint))  
  83.             {  
  84.                 return client.Decrement(key, 1);  
  85.             }  
  86.         }  
  87.     }  

Now, let’s add JsonResult GetCountryList to get the country list to bind the data to the drop-down list.

In this part, we are going to - first, check if the key exists. If not, then we are going we are going to pull data from the database and save it to Redis cache if the key exists then we are going to pull from Redis cache.

In the below code snippet, you can see we are pulling data from SQL database using Entity Framework.

For storing in the Redis Cache, we are passing the key in a generic collection and time span.

Code snippet for storing a collection of data into Redis Cache

  1. public bool StoreList<T>(string key, T value, TimeSpan timeout)  
  2.       {  
  3.           try  
  4.           {  
  5.               using (var redisClient = new RedisClient(_redisEndpoint))  
  6.               {  
  7.                   redisClient.As<T>().SetValue(key, value, timeout);  
  8.               }  
  9.               return true;  
  10.           }  
  11.           catch (Exception)  
  12.           {  
  13.               throw;  
  14.           }  
  15.       }  

Code Snippet for getting the stored value from Redis Cache

  1. public T GetList<T>(string key)  
  2.       {  
  3.           T result;  
  4.   
  5.           using (var client = new RedisClient(_redisEndpoint))  
  6.           {  
  7.               var wrapper = client.As<T>();  
  8.   
  9.               result = wrapper.GetValue(key);  
  10.           }  
  11.   
  12.           return result;  
  13.       }  

Code snippet of getting the Country List for binding drop-down list

  1. public JsonResult GetCountryList()  
  2.         {  
  3.             if (_cacheStrigsStack.IsKeyExists("countryList"))  
  4.             {  
  5.                 var countryList = _cacheStrigsStack.GetList<List<CountryMaster>>("countryList");  
  6.                 return Json(data: countryList, behavior: JsonRequestBehavior.AllowGet);  
  7.             }  
  8.             else  
  9.             {  
  10.                 List<CountryMaster> countryList;  
  11.                 using (var db = new DatabaseContext())  
  12.                 {  
  13.                     var countryListtemp = (from district in db.CountryMaster  
  14.                         select district).ToList();  
  15.   
  16.                     _cacheStrigsStack.StoreList<List<CountryMaster>>("countryList", countryListtemp, TimeSpan.MaxValue);  
  17.                     countryList = _cacheStrigsStack.GetList<List<CountryMaster>>("countryList");  
  18.                 }  
  19.   
  20.                 return Json(data: countryList, behavior: JsonRequestBehavior.AllowGet);  
  21.             }  
  22.   
  23.         }  

After adding a GetCountryList drop-down, next, we are going to add a state dropdown.

Code snippet of getting Country List for a binding drop-down list

We are going to add a state dropdown list which will be the same as a country dropdown. If the key exists, then we are going to pull from Redis Cache and filter on that data. If the key does not exist, then we are going to pull from database and store in the cache.

  1. public JsonResult GetStateList(int? countryId)  
  2.         {  
  3.             if (_cacheStrigsStack.IsKeyExists("stateList"))  
  4.             {  
  5.                 var tempstateList = _cacheStrigsStack.GetList<List<StateMaster>>("stateList");  
  6.                 var stateList = (from state in tempstateList  
  7.                     where state.CountryID == countryId  
  8.                     select state).ToList();  
  9.   
  10.                 return Json(data: stateList, behavior: JsonRequestBehavior.AllowGet);  
  11.             }  
  12.             else  
  13.             {  
  14.                 List<StateMaster> databasestateList;  
  15.   
  16.                 using (var db = new DatabaseContext())  
  17.                 {  
  18.                     databasestateList = (from state in db.StateMaster  
  19.                         select state).ToList();  
  20.                     _cacheStrigsStack.StoreList<List<StateMaster>>("stateList", databasestateList, TimeSpan.MaxValue);  
  21.                 }  
  22.   
  23.                 return Json(data: databasestateList, behavior: JsonRequestBehavior.AllowGet);  
  24.             }  
  25.   
  26.         }  

After adding both the drop-down lists, next, we are going to add a View where we are going to bind this drop-down list with jQuery.

Code snippet of View

We are using jQuery to bind the Country dropdown list and on change of country, we are going to bind the State dropdown list.

  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4.   
  5. <div style="margin-top: 50px;" class="col-md-12">  
  6.     <div class="row">  
  7.         <div class="col-md-6">  
  8.             Country  
  9.             @Html.DropDownList("DrpCountry"new SelectList(string.Empty, "Value""Text"), "Please select a Country"new { @class = "form-control" })  
  10.         </div>  
  11.         <div class="col-md-6">  
  12.             State  
  13.             @Html.DropDownList("DrpState"new SelectList(string.Empty, "Value""Text"), "Please select a State"new { @class = "form-control" })  
  14.         </div>  
  15.     </div>  
  16.     <div class="row">  
  17.         <div class="col-md-4">  
  18.         </div>  
  19.         <div class="col-md-4">  
  20.         </div>  
  21.         <div class="col-md-4">  
  22.         </div>  
  23.     </div>  
  24. </div>  
  25. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  26.   
  27.   
  28. <script type="text/javascript">  
  29.     $(document).ready(function ()  
  30.     {  
  31.         $.ajax({  
  32.             url: '/DemoDropdown/GetCountryList',  
  33.             type: "POST",  
  34.             dataType: 'json',  
  35.             success: function (result) {  
  36.                 $.each(result, function (i, state)  
  37.                 {  
  38.                     $("#DrpCountry").append('<option value="' + state.ID + '">' + state.Name + '</option>');  
  39.                 });  
  40.   
  41.             },  
  42.             error: function (err) {  
  43.                 alert(err.statusText);  
  44.             }  
  45.         });  
  46.   
  47.         $("#DrpCountry").change(function ()  
  48.         {  
  49.             $.ajax({  
  50.                 url: '/DemoDropdown/GetStateList',  
  51.                 type: "POST",  
  52.                 dataType: 'json',  
  53.                 data: { countryId: $("#DrpCountry").val() },  
  54.                 success: function (result) {  
  55.                     $("#DrpState").empty();  
  56.                     $("#DrpState").append('<option value="-1">Please select a State</option>');  
  57.                     $.each(result, function (i, state)  
  58.                     {  
  59.                         $("#DrpState").append('<option value="' + state.ID + '">' + state.Name + '</option>');  
  60.                     });  
  61.   
  62.                 },  
  63.                 error: function (err) {  
  64.                     alert(err.statusText);  
  65.                 }  
  66.             });  
  67.         });  
  68.   
  69.     });  
  70.   
  71.   
  72. </script>  

Output

Use Redis With ASP.NET MVC  

Data Stored in Redis Cache

Use Redis With ASP.NET MVC
 
Multistep Forms

In some applications, a customer has a requirement that until the user does not fill the complete form, it is not considered as submitted. Here, we should keep the data on a temporary basis. Here, Redis comes in to play because you can store the data in Redis cache along with timespan (you can add time for data expiration). Let us say the user-filled data should be only valid for a week and after that, it should get deleted. If you do the same process with any RDBMS, then you require to schedule an SQL job to check which data is expired. Then, you can delete it.

For this demo, we are going to create 2 forms.

The first form will have Name and Email id.

The second form will have Address and Age.

Models that we have added

  1. public class Demo1  
  2. {  
  3.     public string Name { get; set; }  
  4.     public string EmailId { get; set; }  
  5. }  
  6.   
  7. public class Demo2  
  8. {  
  9.     public string Address { get; set; }  
  10.     public string Age { get; set; }  
  11. }  

After adding models, we are going to add a controller with the name “MultiStepController” and in this controller, we are going to keep the user data of multiple forms. In Redis cache, for that, we have generated a UserID which will be stored as uniquid to recognize the users.

  1. public class MultiStepController : Controller  
  2.     {  
  3.   
  4.         private readonly CacheStrigsStack _cacheStrigsStack;  
  5.   
  6.         public MultiStepController()  
  7.         {  
  8.             _cacheStrigsStack = new CacheStrigsStack();  
  9.         }  
  10.   
  11.         // GET: MultiStep  
  12.         [HttpGet]  
  13.         public ActionResult Form1()  
  14.         {  
  15.             Session["_userid"] = Convert.ToString(Guid.NewGuid());  
  16.             return View();  
  17.         }  
  18.   
  19.         [HttpPost]  
  20.         public ActionResult Form1(Demo1 demo1)  
  21.         {  
  22.             var key = Convert.ToString(Session["_userid"]) + ":step1";  
  23.             _cacheStrigsStack.StoreList(key, demo1, TimeSpan.FromMinutes(5));  
  24.             return RedirectToAction("Form2");  
  25.         }  
  26.   
  27.   
  28.         // GET: MultiStep  
  29.         [HttpGet]  
  30.         public ActionResult Form2()  
  31.         {  
  32.             return View();  
  33.         }  
  34.   
  35.         [HttpPost]  
  36.         public ActionResult Form2(Demo2 demo2)  
  37.         {  
  38.             var key = Convert.ToString(Session["_userid"]) + ":step2";  
  39.             _cacheStrigsStack.StoreList(key, demo2, TimeSpan.FromMinutes(5));  
  40.             return View(demo2);  
  41.         }  
  42.     }  

If you see here, we are using the StoreList method for storing the data which takes generic parameters along with the key and timespan. For this form, we have set the timespan to 5 minutes, i.e, this data will be deleted after 5 minutes.

  1. public bool StoreList<T>(string key, T value, TimeSpan timeout)  
  2.       {  
  3.           try  
  4.           {  
  5.               using (var redisClient = new RedisClient(_redisEndpoint))  
  6.               {  
  7.                   redisClient.As<T>().SetValue(key, value, timeout);  
  8.               }  
  9.               return true;  
  10.           }  
  11.           catch (Exception)  
  12.           {  
  13.               throw;  
  14.           }  
  15.       }  

Use Redis With ASP.NET MVC 

Use Redis With ASP.NET MVC

After storing the data, we are going to see in the tools. You can see that TTL (time to live) will get expired in a few minutes.

This snapshot is from the Keylord tool which is a free client that connects to the Redis Server to display all keys and values stored in it.

Step 1 - Data which is stored in the Redis Server

Use Redis With ASP.NET MVC  

Step 2 - Data which is stored in Redis Server

Use Redis With ASP.NET MVC  

After  understanding multiple forms, next, we are going to store the chart's data into the database.

Cache Charts data

In this part, we are going to have a look at how to store charts data into Redis cache for performance, because in most customer-facing websites or all applications which show charts, this data is pulled from the database which may cause performance issues. The query which we write for chart data is bit complex where we take the average count of data. When it is too large this will take a long time to execute  which will  disappoint the end user. 

For this demo, we are going to show a bar chart. For which on the first request we are going to pull data from the database and then keep it in the cache then for all further requests we are going to pull from Redis cache.

Let’s add a controller with name “DashboardController.” Inside this controller we are going to add Bar Chart Action method, next we need to pull data from the database. For doing that I added a Repository folder which Contains Interface (ICharts) and Concentre (ChartsConcrete) class in which I have written logic to get data from the database.

Note
All this source code is available for download along with the database.

Interface Code Snippet

  1. namespace WebRedis.Repository  
  2. {  
  3.     public interface ICharts  
  4.     {  
  5.         void ProductWiseSales(out string mobileCountList, out string productList);  
  6.     }  
  7. }  

Concrete Class Code Snippet

In this part, we are implementing the ICharts interface and its members. For getting the collection we are going to use dapper orm.

  1. using System.Configuration;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Linq;  
  5. using Dapper;  
  6. using WebRedis.Models;  
  7.   
  8. namespace WebRedis.Repository  
  9. {  
  10.     public class ChartsConcrete : ICharts  
  11.     {  
  12.         public void ProductWiseSales(out string mobileCountList, out string productList)  
  13.         {  
  14.             using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString()))  
  15.             {  
  16.                 var productdata = con.Query<ProductModel>("Usp_GetTotalsalesProductwise"nullnulltrue, 0, CommandType.StoredProcedure).ToList();  
  17.   
  18.                 var mobileSalesCounts = (from temp in productdata  
  19.                     select temp.MobileSalesCount).ToList();  
  20.   
  21.                 var productNames = (from temp in productdata  
  22.                     select temp.ProductName).ToList();  
  23.   
  24.                 mobileCountList = string.Join(",", mobileSalesCounts);  
  25.                 productList = string.Join(",", productNames);  
  26.             }  
  27.         }  
  28.   
  29.     }  
  30. }  

After adding interface and a concrete method to get data from the database next we are going to work on Bar chart action method. In this method we are going to call ProductwiseSales method. And then we are going check the if keys of bar charts are exits in Redis Cache; if not then we are going to pull data from the database and then add it to the Redis cache. On the next request we are going pull data from Redis cache.

Dashboard Controller Code Snippet

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using WebRedis.CacheLayer;  
  7. using WebRedis.Repository;  
  8.   
  9. namespace WebRedis.Controllers  
  10. {  
  11.     public class DashboardController : Controller  
  12.     {  
  13.         private readonly ICharts _iCharts;  
  14.         private readonly CacheStrigsStack _cacheStrigsStack;  
  15.         public DashboardController()  
  16.         {  
  17.             _iCharts = new ChartsConcrete();  
  18.             _cacheStrigsStack = new CacheStrigsStack();  
  19.         }  
  20.         // GET: Dashboard  
  21.   
  22.         [HttpGet]  
  23.         public ActionResult BarChart()  
  24.         {  
  25.             try  
  26.             {  
  27.                 string tempMobile;  
  28.                 string tempProduct;  
  29.   
  30.                 if (!_cacheStrigsStack.IsKeyExists("Barchart:Mobile") && !_cacheStrigsStack.IsKeyExists("Barchart:Product"))  
  31.                 {  
  32.                     _iCharts.ProductWiseSales(out tempMobile, out tempProduct);  
  33.                     _cacheStrigsStack.StoreList("Barchart:Mobile", tempMobile, TimeSpan.FromDays(1));  
  34.                     _cacheStrigsStack.StoreList("Barchart:Product", tempProduct, TimeSpan.MaxValue);  
  35.                     ViewBag.MobileCount_List = tempMobile.Trim();  
  36.                     ViewBag.Productname_List = tempProduct.Trim();  
  37.                 }  
  38.                 else  
  39.                 {  
  40.                     tempMobile = _cacheStrigsStack.GetList<string>("Barchart:Mobile");  
  41.                     tempProduct = _cacheStrigsStack.GetList<string>("Barchart:Product");  
  42.                     ViewBag.MobileCount_List = tempMobile.Trim();  
  43.                     ViewBag.Productname_List = tempProduct.Trim();  
  44.                 }  
  45.   
  46.                 return View();  
  47.             }  
  48.             catch (Exception)  
  49.             {  
  50.                 throw;  
  51.             }  
  52.         }  
  53.     }  
  54. }  

After adding action method, next we are going to add View and, on that View, we are going to use Chart.js to display charts.

Dashboard Controller Code Snippet

On view, we just place data to display charts.

  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>  
  2. <script>  
  3.     var barChartData =  
  4.     {  
  5.         labels: [@Html.Raw(ViewBag.Productname_List)],  
  6.         datasets: [{  
  7.             label: 'ProductWise Sales Count',  
  8.             backgroundColor: [  
  9.                 "#f990a7",  
  10.                 "#aad2ed",  
  11.                 "#9966FF",  
  12.                 "#99e5e5",  
  13.                 "#f7bd83",  
  14.             ],  
  15.             borderWidth: 2,  
  16.             data: [@ViewBag.MobileCount_List]  
  17.         }]  
  18.     };  
  19.   
  20.     window.onload = function () {  
  21.         var ctx1 = document.getElementById("barcanvas").getContext("2d");  
  22.         window.myBar = new Chart(ctx1,  
  23.             {  
  24.                 type: 'bar',  
  25.                 data: barChartData,  
  26.                 options:  
  27.                 {  
  28.                     title:  
  29.                     {  
  30.                         display: true,  
  31.                         text: "ProductWise Sales Count"  
  32.                     },  
  33.                     responsive: true,  
  34.                     maintainAspectRatio: true  
  35.                 }  
  36.             });  
  37.     }  
  38. </script>  
  39.   
  40. <div style="width: 700px; height: 700px">  
  41.     <div style="text-align: center">  
  42.         <canvas id="barcanvas"></canvas>  
  43.     </div>  
  44.     <div style="text-align: center">  
  45.         Disclaimer:- This data is for the demo. It is  
  46.         not real data and not related to any company.  
  47.     </div>  
  48. </div>  

We have completed adding View and Controllers, so let’s run the application and check the output.

Use Redis With ASP.NET MVC  

Let’s see the code in debug mode.

We are not jumping into the if block, we are jumping into the else block because the keys are added to Redis cache.

Use Redis With ASP.NET MVC  

If you want to view what is stored in Redis Cache Use Keylord Tool. Just enter port, host and Connection Name to Connect.

Use Redis With ASP.NET MVC  

This will save a lot of resources of SQL Server or My SQL server.

Next we are going to work on the last part which is Session Provider.

Session Provider

In this part, we are going to learn how to store session in out-proc in Redis Cache.

For storing session in out-proc, first we are going to add NuGet package “Microsoft.Web.RedisSessionStateProvider”.

Use Redis With ASP.NET MVC  

After installing “Microsoft.Web.RedisSessionStateProvider” it will add sessionState tags in web.config file.

Use Redis With ASP.NET MVC  

Next, we are going to add the host “127.0.0.1” and make SSL false because we are going to run this application locally. If we run it on production, then make SSL = true.

  1. <system.web>  
  2.     <compilation debug="true" targetFramework="4.5.2" />  
  3.     <httpRuntime targetFramework="4.5.2" />  
  4.     <sessionState mode="Custom" customProvider="MySessionStateStore">  
  5.       <providers>  
  6.         <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" />  
  7.       </providers>  
  8.     </sessionState>  
  9.   </system.web>  

After making the changes in the application, next, let's store the some values in Session and check if it gets stored in Redis Cache.

Next, for the demo, we are going to add “DemoController” and in that controller, we are going to add Index action Method. In this method we are going set session and get value from the session.

Code Snippet of Controller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace WebRedis.Controllers  
  8. {  
  9.     public class DemoController : Controller  
  10.     {  
  11.         // GET: Demo  
  12.         public ActionResult Index()  
  13.         {  
  14.             Session["Username"] = "Saineshwar Bageri";  
  15.             Session["UserID"] = Convert.ToString(Guid.NewGuid());  
  16.   
  17.             return View();  
  18.         }  
  19.     }  
  20. }  

 After storing value, we are going to display stored session values on View.

Code Snippet of View

  1. @model dynamic  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html>  
  6. <head>  
  7.     <title>title</title>  
  8.       
  9. </head>  
  10. <body>  
  11. <div class="container">  
  12.     <div style="margin-top:30px;" class="row">  
  13.         Username:-  @Session["Username"]  
  14.     </div>  
  15.       
  16. </div>  
  17. </body>  
  18. </html>  

Output

Use Redis With ASP.NET MVC  

After displaying the value on View, next we are going see how these values are stored IN Redis Cache.

Use Redis With ASP.NET MVC  

Session Timeout stored in Redis Cache.

Use Redis With ASP.NET MVC  

In this way, we can store and use Redis Session Provider. If we have hosted an application on multiple Web servers then we need a common session store where we can keep the session. If we have kept Session in in-proc, then the user will find the session only on the single web server. If he gets another server, then he needs to again sign into that web server to get a session where the state of the user is not maintained.

Note

You can also Use Linux hosted Redis Cache with ASP.NET to try this example. You do not need to change the code, just change the port and host in web.config.