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 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.
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Born To Be BomPosted Dec 6, 2019, 4:24 AM
Thank you. Additional, Login class must not be in same controller with MyController in example.
Baba AlexanderPosted Nov 29, 2019, 1:37 AM
I am new in coding and i want to add a session timeout on my mvc code i cant find it anywhere they only talk of extending
Lu SanchezPosted May 17, 2019, 5:56 AM
HttpContext ctx = HttpContext.Current; is not being used...
R VPosted Jan 24, 2019, 10:55 PM
Didn't work.. HttpContext.Current.Session["userId"] has thrown null. I've session["userId"] when user logs into application but session is always null in action filter attribute. Can you help?