Question

I have defined a custom authorization attribute. In order to avoid listing the attribute above every ActionResult in my Controller(s), I’ve added the attribute to my global.asax as follows:

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

An unintended consequence of this, however, is that my authorization code is getting called during all of my JsonResult calls as well. Is there a way for MyAuthorizeAttribute to get invoked ONLY on ActionResult calls and NOT on JsonResult calls? I'm using MVC3.

Was it helpful?

Solution

Does the filter run before or after the action method?

If it runs before, you can't know what concrete type will be returned, because all actions return ActionResult (unless you specifically return JsonResult - that's another story).

If it runs after the action method, then in your filter code check whether the result is a JsonResult, like that:

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (!(filterContext.Result is JsonResult))
        {
            // do whatever you want...
        }

        base.OnResultExecuting(filterContext);
    }

OTHER TIPS

I disagree with the previous answer. You seem to have approached this from the wrong end. You should be looking at the request type, not the return type.

You can check for Ajax requests before the action in your filter. You should have something like this...

public class MyAuthorizeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
            return;

        // else do authorisation stuff...
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top