Update Session Values On Each Request In C#

In this article, we will learn how we can update sessions or perform similar operations on each request in C# or any language. we just need to create middleware that executes on each request. Here I’m taking an example of MVC.

In your MVC application create one class(middleware) and give a relevant name. here I’ll assign the name “SessionFilter”. Once created copy the below code and paste into that class.

using System.Web;
using System.Web.Mvc;

namespace SessionFilterDemo.Models
{
    public class SessionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            HttpRequestBase request = filterContext.HttpContext.Request;
            if (HttpContext.Current.Session["UserInfo"] == null)
            {
                HttpContext.Current.Session["UserInfo"] = "faisal";
            }           

        }
    }
}

Now, We need to register this filter somewhere depnds on technogy. In MVC I’ll register “SessionFilter” globally in RegisterGlobalFilters method of FilterConfig.cs file.

Your FilterConfig.cs file will look like this

using SessionFilterDemo.Models;
using System.Web.Mvc;

namespace SessionFilterDemo
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new SessionFilter());
        }
    }
}

And you have done with it. Now whetever you want to perform in middel of request you can do with help of SessionFilter class.

hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories