.NET

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.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago