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?
The Controller consists of the following two Action methods. Inside this Action method, simply the View is returned. When the Get SessionId Button is clicked, SetSession Action method is executed which saves the value to the Session using the SetString method. Then the Session ID is retrieved from HttpContext.
In asp.net, It is very simple to detect session time out and redirect the user to login page or home page. All you have to do is, specify the redirection page in session_start event handler in Global. asax file as shown below. If the session has timed out, the user will be redirected to the login page.
In MVC the controller decides how to render view, meaning which values are accepted from View and which needs to be sent back in response. ASP.NET MVC Session state enables you to store and retrieve values for a user when the user navigatesto other view in an ASP.NET MVC application.
An action (or action method) is a method on a controller which handles requests. Controllers logically group similar actions together. This aggregation of actions allows common sets of rules, such as routing, caching, and authorization, to be applied collectively. Requests are mapped to actions through routing.
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()
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With