ASP.NET Web API 不返回自定义错误信息

How*_*amp 1 asp.net asp.net-mvc asp.net-web-api asp.net-web-api2

我有一个 ASP.NET Web API 2 操作方法:

[System.Web.Http.HttpPost]
public HttpResponseMessage Create(HttpRequestMessage req)
{
   //...

   if (success)
      return Request.CreateResponse(HttpStatusCode.Created);

   return CreateErrorResponse(HttpStatusCode.BadRequest, "you done bad");
}
Run Code Online (Sandbox Code Playgroud)

直到我做了“某事”,一旦出错,它就会返回 http 400,并带有自定义错误文本“you did bad”。这就是预期的结果。

它不再返回自定义文本;它只是返回标准的“错误请求”。一直在试图了解是什么改变导致了这种情况的发生。

所以我尝试:

var response = new { message = "you done bad" };
return Request.CreateResponse(HttpStatusCode.BadRequest, response);
Run Code Online (Sandbox Code Playgroud)

相同的结果。

然后我创建了一个新的、干净的 Web API 项目,并得到了我期望的结果。

我是如何破坏我的项目的?

How*_*amp 5

该问题与 web.config 中的 CustomErrors 配置有关。来自 @HaukurHaf 在Error messages returned from Web API method are obliged in non-devenvironment的回答:

有同样的问题。确实是因为自定义错误设置。

在现实场景中,您肯定希望在应用程序中使用自定义错误页面,但为了使自定义异常消息在 WebAPI 中工作,您需要禁用自定义错误页面。

如何解决这个问题?幸运的是,您可以使用<location>web.config 中的元素来解决这个问题。

解决方案:

 <!-- General for the application -->
  <system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="YourCustomErrorPage.aspx"/>
  </system.web>

  <!-- Override it for paths starting with api (your WebAPI) -->
  <location path="api">
     <system.web>
        <customErrors mode="Off" />
     </system.web>
  </location>
Run Code Online (Sandbox Code Playgroud)

我在自己的应用程序中使用了这个方法,效果很好。

虽然我确实看到这是有效的,但我不明白为什么 CustomErrors 部分会破坏它。