关于 c#:ASP.NET MVC 在发送状态为 500 的响应时显示错误页面 | 珊瑚贝

ASP.NET MVC showing error page on when sending responses with status 500


我在服务器中有以下动作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[HttpPost]
public JsonResult SearchContracts(SearchViewModel vm)
{
    List<string> errors;

    if (IsValid(vm, out errors))
    {
        return Json(service.Search(vm), JsonRequestBehavior.AllowGet);
    }
    else
    {
        HttpContext.Response.StatusCode = 500;

        return Json(new { Errors = errors }, JsonRequestBehavior.AllowGet);
    }
}

在本地,效果很好。当请求无效时,它会返回一个带有错误的 JSON,并且响应中有一个用于 HTTP 状态代码的 500。

部署后,IIS 将返回这个著名的错误页面,而不是描述的 JSON。

这里是 web.config 以及 customErrors 部分的详细信息:

1
2
3
<customErrors mode=“Off” defaultRedirect=“~/error.htm”>
    <error statusCode=“404” redirect=“~/errorhandling/pagenotfound” />
</customErrors>

我试着把它改成 On 但都没有成功。

我应该在哪里更改以停止接收那个丑陋的错误页面而不是我的美丽 JSON?

编辑:

我将状态代码更改为 400,现在我得到文本 Bad Request 作为响应,而不是 JSON:

Bad

  • 简单不要使用暗错误 500 向用户通知模型的无效状态,它旨在用于服务器端出现问题但服务器本身无法告诉您错误的情况。例如,访问邮件服务器或类似的东西时访问被拒绝。


来自这个链接:

解决了编辑web.config并添加以下属性:

1
2
3
4
5
<system.webServer>
   
    <httpErrors existingResponse=“PassThrough”></httpErrors>
   
</system.webServer>

另一个离奇的微软故事。


您使用的是服务器错误而不是客户端错误。根据 5XX 错误的维基百科:

“The server failed to fulfill an apparently valid request.”

在这种情况下,您的服务器工作正常,客户端发送错误请求。请改用客户端错误 (4XX)。

  • 我对其进行了编辑,但现在我得到了文本 Bad Request :( 请查看我的问题已更新


如果您需要同时使用自定义错误页面并有时返回 httpErrors 部分中定义的 http 状态的自定义数据,请执行以下操作:
– 在 web.config 中设置 existingResponse=”Auto”(httpErrors 部分,这是您定义自定义错误页面的地方);
– 在您的操作中设置 TrySkipIisCustomErrors = true(返回 4xx 状态和内容的操作);
– 清除 global.asax 中的服务器错误(在 Application_Error() – Server.ClearError() 中)并重新设置状态代码 (Reponse.StatusCode = ((HttpException)Server.GetLastError()).GetHttpCode())


来源:https://www.codenong.com/27782635/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9895.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?