Mayur Lohite Published a new article on Web, Mobile & Software Dev, Web Development, Web & Mobile Design
14-Sep-2019
In a dynamic web application, the session is crucial to hold the information of current logged in user identity/data. So someone without authentication cannot have access to some Page
or any ActionResult
, to implement this kind of functionality, we need to check session exists (is not null
) in every action which required authentication.
[HttpGet] public ActionResult Home() { if(Session["ID"] == null) return RedirectToAction("Login","Home"); }
We have to check the above 2 statements each time and in each ActionResult
, but it may cause 2 problems.
The ASP.NET MVC provides a very great mechanism i.e., Action Filters. An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
If you want to know more about action filter, please click here.
So we will create a custom Action Filter that handles session expiration and if session is null
, redirect to Login Action.
Create a new class in your project and copy the following code:
namespace Mayur.Web.Attributes { public class SessionTimeoutAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; if (HttpContext.Current.Session["ID"] == null) { filterContext.Result = new RedirectResult("~/Home/Login"); return; } base.OnActionExecuting(filterContext); } } }
Now our Action Filter is created and we are ready to use it. The following code will show you how we can apply attribute to Action
or to complete controller.
[HttpGet] [SessionTimeout] public ActionResult MyProfile() { return View(); }
[SessionTimeout]
public class HomeController : Controller
{
[HttpGet]
public async ActionResult MyProfile()
{
return View();
}
[HttpGet]
public async ActionResult MyQuestions()
{
return View();
}
[HttpGet]
public async ActionResult MyArticles()
{
return View();
}
}
Now all actions of Home Controller will check for session when hit with the help of Action Filter. So we have reduced the code and repetitive things. This is the benefits of Action Filters.
Happy coding !!!