如何从HandleError过滤器返回JSON?

时间:2008-09-21 00:32:49

标签: asp.net-mvc

aspnet mvc有HandleError过滤器,如果发生错误将返回一个视图,但如果在调用JsonResult时发生错误,Action如何返回表示错误的JSON对象?

我不想在每个在try / catch中返回JsonResult的动作方法中包装代码来完成它,我宁愿通过添加'HandleJsonError'属性或使用现有的HandleError属性来实现它。必要的行动方法。

3 个答案:

答案 0 :(得分:10)

看一下HandleErrorAttribute的MVC实现。它返回一个ViewResult。您可以编写自己的版本(HandleJsonErrorAttribute)来返回JsonResult。

答案 1 :(得分:7)

简而言之,要走的路可以是扩展HandleErrorAttribute,如下所示:

public class OncHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        // Elmah-Log only handled exceptions
        if (context.ExceptionHandled)
            ErrorSignal.FromCurrentContext().Raise(context.Exception);

        if (context.HttpContext.Request.IsAjaxRequest())
        {
            // if request was an Ajax request, respond with json with Error field
            var jsonResult = new ErrorController { ControllerContext = context }.GetJsonError(context.Exception);
            jsonResult.ExecuteResult(context);
            context.ExceptionHandled = true;
        }
        else
        {
            // if not an ajax request, continue with logic implemented by MVC -> html error page
            base.OnException(context);
        }
    }
}

如果您不需要,请删除Elmah日志记录代码行。我使用我的一个控制器根据错误和上下文返回一个json。以下是样本:

    public class ErrorController : Controller
{
    public ActionResult GetJsonError(Exception ex)
    {
        var ticketId = Guid.NewGuid(); // Lets issue a ticket to show the user and have in the log

        Request.ServerVariables["TTicketID"] = ticketId.ToString(); // Elmah will show this in a nice table

        ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling

        ex.Data.Add("TTicketID", ticketId.ToString()); // Trying to see where this one gets in Elmah

        return Json(new { Error = String.Format("Support ticket: {0}\r\n Error: {1}", ticketId, ex.ToString()) }, JsonRequestBehavior.AllowGet);
    }

我在上面添加了一些故障单信息,你可以忽略它。由于实现了过滤器的方式(扩展了默认的HandleErrorAttributes),我们可以从全局过滤器中删除HandleErrorAttribute:

    public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new GlobalAuthorise());
        filters.Add(new OncHandleErrorAttribute());
        //filters.Add(new HandleErrorAttribute());
    }

基本上就是这样。您可以阅读my blog entry了解更多详细信息,但是对于这个想法,上面就足够了。

答案 2 :(得分:1)

也许您可以创建自己的Attribute并使用一个构造函数值,该值采用View或Json的枚举值。以下是我用于自定义授权属性以证明我的意思。这种方式,当json请求的身份验证失败时,它会以json错误响应,如果返回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()
    {
    }