17

I am using an ActionFilter to determine if a user has access to a specific resource such as an Account object (a la Rhino Security) before hitting an action. This is a global filter which redirects to an error page should the authorization value fail

I'm using the following code, which works fine for full page requests:

filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
filterContext.Result = new RedirectResult("~/Error/AuthorizationError");

Ajax requests I do not want to apply a redirect, but rather return an error message. Is there a way to tell inside the action filter if this is an AJAX request or a regular full page (sorry not sure of the correct terminology) request?

Thanks in advance

JP

1 Answer 1

40

You could use the IsAjaxRequest extension method:

if (filterContext.HttpContext.Request.IsAjaxRequest())
{
    // it was an AJAX request
    ...
}
else
{
    // it was a standard request
    filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
    filterContext.Result = new RedirectResult("~/Error/AuthorizationError");
}
Sign up to request clarification or add additional context in comments.

2 Comments

This looks like exactly what we're trying to do. But...for some reason that condition filterContext.HttpContext.Request.IsAjaxRequest() isn't coming back true when it's an AJAX request. Also...how would you redirect the user to a new page from an ajax request?
@bubbleking I wish I had a good answer for you. I can't even remember what page we were trying with this. Sorry :(

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.