0

I basically want to check if the session is still valid for every GET and POST request in my application, however, I don't really want to keep copying and pasting the same code in to every Action Method, I was thinking of using a Base Controller so I can inherit the usage or a static helper controller class (if this can be done??). Are either of these ways the best (or even correct) approach to take?

Example of code

    [HttpGet]
    [ValidateInput(false)]
    public ActionResult SimpleSearch()
    {
        // I want to run this code of every ActionResult for a GET AND POST
        if (!SessionStaticClass.IsUserLoggedIn())
        {
            return RedirectToAction("Login, Login");
        }
    }

Thanks

4
  • Which version of MVC are you using? Commented Oct 14, 2014 at 14:03
  • 5 - well the latest I believe Commented Oct 14, 2014 at 14:04
  • 1
    If you're using session to store login information, you are doing it very wrong, and making your site very insecure... Commented Oct 14, 2014 at 14:34
  • 1
    Don't worry I am not, no usernames or passwords in my session baby! Commented Oct 14, 2014 at 15:03

1 Answer 1

2

You can use an action filter:

public class NotLoggedInFilter : FilterAttribute, IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
         if (!SessionStaticClass.IsUserLoggedIn())
         {
             filterContext.Result = new RedirectToAction("Login, Login");
         }
    }
}

You can then decorate controllers or actions with the attribute, or even have it run for all actions by adding it to the global filter collection.

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{    
    filters.Add(new NotLoggedInFilter());
}

However, you might want to have a look at authentication filters as a way of handling user authentication instead of using the SessionStaticClass class. A good overview of filter types in MVC can be found here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.