tags:

views:

30

answers:

1

I have a C# MVC application that relies heavily on Ajax. I am using the Ext JavaScript framework but that's not important here.

If a logged on user is on a page and their session times out I need to inform the user this has happened at their very next Ajax request.

For example there is a combo box that does an auto search and displays results. If the session times out and they enter information into this box an Ajax request is posted to the server. Before the action is executed I want to determine that they are not logged in and return a message inside a JSON object detailing the reason for the failure so that I can create a pop up or redirect.

For bonus points it would be easier if I don't have to implement this solution in the 300 or so Actions that I have. An attribute on the class or method would be a good solution and inline with what I currently do for non Ajax 'GET' requests.

A: 

This is the solution I have come up with

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
sealed public class RedirectIfUserNotLoggedOnAttribute : ActionFilterAttribute
{
public override void OnActionExecuting (ActionExecutingContext filterContext)
  {
    if (!IsUserLoggedOn)
        {
          filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                                                                                      {
                                                                                        controller = "User",
                                                                                        action = "WarnLogOutAsJson",
                                                                                      }));
        }
}
}

The controller action you specify should return a JsonResult.

Ofcourse you would need to create a different attribute for GET requests or any other request where the response was not ecpected in Json form.

Jonnio