Click here to Skip to main content
15,891,694 members
Articles / Programming Languages / C#

Check Session Timeout by Using ActionFilters in MVC

Rate me:
Please Sign up or sign in to vote.
4.47/5 (8 votes)
2 Jan 2024CPOL1 min read 87.4K   12   4
How to check session timeout by using ActionFilters in MVC

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.

So, the general method is as follows:
C#
[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.

  1. Repeat Things: As per the good programming stranded, we don't have to repeat the things. Create a module of common code and access it multiple times/repeatedly
  2. Code missing: We have to write code multiple times so it might happen some time we forget to write code in some method or we missed it.

How To Avoid?

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:

C#
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.

1. Apply to Action

C#
[HttpGet]
[SessionTimeout]
public ActionResult MyProfile()
{
    return View();
}

2. Apply to Controller

C#
[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 !!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
My name is Mayur Lohite. I am Programmer and Web Developer also I am Interested in Web Application Security and penetration. From a young age I’ve been fascinated with building web application and breaking it. So I have choose the Information technology as my career and completed the Degree in Information technology.

I’m a interested in operating and design of large-scale web applications/infrastructure and I’m interested in web application security also I am interested in some networking setting up servers, domains experimenting with clouds(well I am not professional at it)

I am a big fan of Anime series (Naruto) and also love to playing games. In the mean time I love to watching movies specially action movies.

Now I’m a white hat penetration tester. bug hunter and all out security freak by profession and passion. I’ve listed many websites Hall of fame e.g. Microsoft, Yahoo, Apple, Adobe

Comments and Discussions

 
QuestionGreat article. Is it possible to set different timeouts for different roles? Pin
nirmalamari4-Jan-24 2:08
nirmalamari4-Jan-24 2:08 
QuestionAfter Session TimeOut Login is not working Pin
Member 1404004228-Dec-22 2:24
Member 1404004228-Dec-22 2:24 
QuestionLogin SessionTimeout Pin
Member 114879765-Dec-19 23:10
Member 114879765-Dec-19 23:10 
Questionreturn to page Pin
RaunakGupta30-Sep-16 1:07
RaunakGupta30-Sep-16 1:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.