当HTTP状态为错误请求

时间:2016-02-04 20:24:54

标签: c# asp.net asp.net-mvc-4 asp.net-web-api

var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
    Content = new StringContent("Error in Validation"),
    ReasonPhrase = "Error in Validation"
};
throw new HttpResponseException(response);

上面的代码没有返回“验证错误”,因为响应内容会返回“错误请求”。

string result = response.Content.ReadAsStringAsync().Result;

我可以从ReasonPhrase中读取它,但有些客户希望在响应正文中显示错误消息。如果HTTP状态设置为OK,则它将返回正确的消息。

2 个答案:

答案 0 :(得分:0)

您可以考虑使用System.Net.Http命名空间中的HttpRequestMessageExtensions.CreateErrorReponse。

讨论了类似的问题here.

答案 1 :(得分:0)

能够修复它,以防有人遇到同样的问题。我有共存的网站和API,问题是由于自定义错误页面转发。

 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" />     
</httpErrors>

我必须在Web.config中添加以下部分来解决问题。

<location path="api">
<system.webServer>      
  <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
    <clear/>
  </httpErrors>
</system.webServer>