Check Session on all actions of controller

8.9k views Asked by At

I have an simple MVC app I want to check first the session as this action

 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?

1

There are 1 answers

0
Usman On

you can use OnActionExecuting and can also override this method to write custom logic so create a class

 public class SessionCheck: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpSessionStateBase session = filterContext.HttpContext.Session;
            if (session != null && session["UserInfo"] == null)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {
                                { "Controller", "Users" },
                                { "Action", "Login" }
                                });
            }
        }
    } 

add namespaces in the class

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

and in your controller add [SessionCheck] attribute like this

 [SessionCheck]
 public class HomeController : Controller
  {
  }

this will check session on all the actions of controller or you can also add this attribute on action like this

[SessionCheck]
public ActionResult Index()
 {
 }