In web applications, session holds the information of current logged-in users. So, if the session expires in 20 minutes, then it is redirected to login page. In that case, we need to check if session exists (not null) in every action/ every controller which requires authentication.
We have to two methods to check.
- We can check in every ActionResult.
- We can check in every controller.
The first option is not good because it gets repeated every time. So, avoid it and use the second option.
We will create one custom Action Filter that handles session expiration and if session is null, it redirects to Login Action.
- namespace WebApplication.Filters {
- public class SessionTimeoutAttribute: ActionFilterAttribute {
- public override void OnActionExecuting(ActionExecutingContext filterContext) {
- HttpContext ctx = HttpContext.Current;
- if (HttpContext.Current.Session["userId"] == null) {
- filterContext.Result = new RedirectResult("~/User/Login");
- return;
- }
- base.OnActionExecuting(filterContext);
- }
- }
- }
Now, our Action Filter is created and we are ready to use it.
Apply to Controller
- [SessionTimeout]
- public class MyController: Controller {
- [HttpGet]
- public ActionResult Index() {
- return View();
- }
- [HttpGet]
- public ActionResult Home() {
- return View();
- }
- }
Now, all the action methods are authenticated in this Controller. So whenever a session expires, the user is redirected on the login page.