tags:

views:

486

answers:

2

aspnet mvc has the HandleError filter that will return a view if an error occurs, but if an error occurs when calling a JsonResult Action how can I return a JSON object that represents an error?

I don't want to wrap the code in each action method that returns a JsonResult in a try/catch to accomplish it, I'd rather do it by adding a 'HandleJsonError' attribute or using the existing HandleError attribute to the required action methods.

A: 

Maybe you could create your own Attribute and have a constructor value that takes an enum value of View or Json. Below is what Im using for a custom Authorization Attribute to demonstrate what I mean. This way when authentication fails on a json request it responds with a json error and the same with if it returns a View.

   public enum ActionResultTypes
   {
       View,
       Json
   }

    public sealed class AuthorizationRequiredAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        public ActionResultTypes ActionResultType { get; set; }

        public AuthorizationRequiredAttribute(ActionResultTypes actionResultType)
        {
            this.ActionResultType = ActionResultType;
        }
    }

    //And used like
    [AuthorizationRequired(ActionResultTypes.View)]
    public ActionResult About()
    {
    }
Vyrotek
I'm going to try and implement a working example. If you find out it doesnt work or find a different solution please let me know!
Vyrotek
+2  A: 

Take a look at the MVC implementation of HandleErrorAttribute. It returns a ViewResult. You could write your own version (HandleJsonErrorAttribute) that returns a JsonResult.

Haacked
I've tried this but when the HandleJsonErrorAttribute OnException method is called the filterContext.ExceptionHandled property is always true when theres a HandleErrorAttribute on the Controller class the action belongs to. Shouldn't the action methods handleerror take priority and be called first?
Luke Smith