HTTP状态为“错误请求"时,HttpResponseMessage内容丢失 [英] HttpResponseMessage content lost when HTTP Status is Bad Request

查看:321
本文介绍了HTTP状态为“错误请求"时,HttpResponseMessage内容丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上面的代码没有返回验证错误"作为响应内容,而是返回了错误请求".

The above code is not returning "Error in Validation" as response Content instead returns "Bad Request".

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

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

I can read it from the ReasonPhrase but some customers want the error message in the response body. If HTTP Status is set as OK then it will return the correct message.

推荐答案

可以解决此问题,以防有人遇到相同的问题.我有网站和API共存,问题是由于自定义错误页面转发所致.

Was able to fix it, in case someone has same issue. I have coexisting website and API and the problem was due to custom error page forwarding.

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

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

I have to add below section to the Web.config to solve the problem.

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

这篇关于HTTP状态为“错误请求"时,HttpResponseMessage内容丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆