I have an simple MVC app I want to check first the session as this action
C#
public ActionResult Index()
{
if (Session["UserInfo"] == null)
{
return RedirectToAction("Login", "Users");
}
return View();
}My question is about is there a way to enforce this check to all actions without do it manual for each action?


Amit MohantyRank #112 · 20K reputationPosted Aug 8, 2023, 2:08 AM EDT
Yes, you can enforce this check for all actions in your MVC application without manually adding the session check to each action by using a custom action filter. Action filters are attributes that can be applied globally to controllers or actions, allowing you to perform common tasks like session checks in a centralized manner.
Create a new class for your custom action filter attribute. Let's call it SessionCheckAttribute.
using System; using System.Web.Mvc; public class SessionCheckAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var session = filterContext.HttpContext.Session; if (session["UserInfo"] == null) { filterContext.Result = new RedirectResult("~/Home/Login"); } base.OnActionExecuting(filterContext); } }Apply the custom attribute to your controller or actions where you want the session check to be enforced:
[SessionCheck] // Apply the custom attribute at the controller level public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult AnotherAction() { return View(); } } //OR public class HomeController : Controller { [SessionCheck] // Apply the custom attribute at the action level public ActionResult Index() { return View(); } public ActionResult AnotherAction() { return View(); } }Cr BhargaviRank #420 · 5.9K reputationPosted Aug 8, 2023, 4:26 AM EDT
using System; using System.Web; using System.Web.Mvc; public class SessionCheckFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpSessionStateBase session = filterContext.HttpContext.Session; if (session["UserInfo"] == null) { filterContext.Result = new RedirectResult("~/Users/Login"); } base.OnActionExecuting(filterContext); } }