【问题标题】:Handling Exceptions in MVC JSON Controller Action处理 MVC JSON 控制器操作中的异常
【发布时间】:2012-05-19 11:23:40
【问题描述】:

我正在寻找在返回 JSON 结果时处理控制器中的错误的最佳方法。

首先,如果我在控制器中遇到未处理的异常并且返回 JSON,那么最佳做法是什么?我在想 400 或 500 错误?客户端检查状态并执行任何操作。

我正在使用 FilterAttribute 和 IExceptionFilter 但我无法调用 OnException 函数。我已将该属性应用于控制器操作。

有什么想法可能不会调用吗?

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class AjaxHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
    // This is never called !!!
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (filterContext.Exception != null 
            && !filterContext.ExceptionHandled)
        {
            ...
            filterContext.HttpContext.Response.StatusCode = 400;
            filterContext.HttpContext.Response.StatusDescription = "Error processing                 request";
            ...
        }
    }
}

public class MyController : Controller
{
    public MyController(IMyRepository repo)
    {
        ...
    }

    [AjaxHandleError]
    public ActionResult GetSomeJson(int anId)
    {
        throw new System.Exception();
    }
}

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您应该使用该属性或在您需要添加的 global.asax.cs 中装饰您的控制器

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

    您的 OnException 方法将被调用。

    【讨论】:

      猜你喜欢
      • 2013-06-07
      • 1970-01-01
      • 2014-07-04
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多