Ryand.Johnson
Ryand.Johnson

Reputation: 1906

Error on ActionFilterAttribute when AJAX call is made

I am using a ActionFilter to check if a User's session is the most current session for that user. If they have signed in with another session then the old session is invalid. So, I am checking each action as it is called and signing them out if they are not using the most current session. The problem I am having is that my approach does not work with AJAX calls. The normal GET or POST calls work fine.

public class DuplicateLoginFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var user = Membership.GetUser(HttpContext.Current.User.Identity.Name);
        if (user != null)
        {
            if (!PortalDA.GetUserSession(user.UserName).Trim().Equals(HttpContext.Current.Session.SessionID))
            {

                FormsAuthentication.SignOut();
                filterContext.Result = new RedirectResult(@"\Home\SessionExprired");
            }
        }
        base.OnActionExecuting(filterContext);
    }

I guess my biggest problem to solving this is that I get an error but I can't catch it any where.

I have custom Errors turned On in the webconfig. I am overriding the OnException event in all my controllers. I am also overriding the Application_Error event in the global.asax.

I have stepped through the code, when I make an AJAX call, I return the SessionExpired View. But somewhere after that the error occurs and I can't step any further. The error is never caught in the error events that were overridden. And I get sent to the custom Error page.

I suspect it has something to do with the HTTPHeaders but I don't understand enough about them to know how to fix it if it is AJAX call.

Thanks!

Upvotes: 0

Views: 1212

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

Try redirecting using your routes and not hardcoding the url:

filterContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new 
    {
        controller = "Home",
        action = "SessionExpired"
    }
));

Then make sure that the SessionExpired action exists on HomeController along with the corresponding view and that this action is hit. Obviously since you are redirecting inside an AJAX call, all that you will get in the success callback of your AJAX call is the HTML of this SessionExpired view passed as argument. Don't expect the browser to redirect. You will have to use window.location.href to manually redirect the browser. That's the reason why in this case (the AJAX one) it is better to return a Json result instead of redirecting to a session expired action. Then on the client side you could perform the redirect manually.

Upvotes: 1

Related Questions