【问题标题】:MVC rest API status code 500 with JSON return带有 JSON 返回的 MVC REST API 状态代码 500
【发布时间】:2012-11-25 14:43:47
【问题描述】:

我正在 MVC3 上开发一个 REST API。
每当验证出现问题时,我想抛出 500 + json 来描述错误(json 可以是未验证字段的列表)。
问题是 json 在包含整个 HttpExeption (Server Error in '/' Application.)
如果我输入filterContext.ExceptionHandled = true;,消息就会干净,但客户端看不到他身边的 500 错误。 本例:https://stackoverflow.com/a/4707762/936651实际上是html并将干净的json提供给客户端,但也消除了500错误。

【问题讨论】:

  • 你看过mvc 4 web api了吗?如果你愿意改变框架,我认为有一种内置的方式来做你描述的事情。还有一种更简单的方法来构建 API。

标签: asp.net-mvc rest httpexception


【解决方案1】:

您可以在 seen here 的自定义错误处理程序中将状态代码设置为 500:

filterContext.RequestContext.HttpContext.Response.StatusCode = 500;

在客户端:

$.ajax({
    url: '/home/foo',
    success: function (result) {
        alert('success');
    },
    error: function (jqXHR, textStatus, errorThrown) {
        var json = $.parseJSON(jqXHR.responseText);
        // TODO: do something with the json that was returned from the server
    }
});

【讨论】:

  • 我认为您没有阅读或理解我的整个帖子(-:您将我发布的链接发给我。如果您有时间请重新阅读,谢谢伙计!
  • 您是否将filterContext.RequestContext.HttpContext.Response.StatusCode = 500; 行添加到我之前帖子中显示的MyErrorHandlerAttribute 中?当你这样做时发生了什么?在我之前的帖子中,这一行丢失了,因此错误处理程序从未在 AJAX 请求上命中也就不足为奇了。所以请再仔细阅读我的回答。
猜你喜欢
  • 1970-01-01
  • 2012-07-07
  • 2014-10-26
  • 2014-02-08
  • 1970-01-01
  • 2017-07-10
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多