HttpResponseMessage content lost when HTTP Status

2019-07-15 06:03发布

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;

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.

2条回答
Rolldiameter
2楼-- · 2019-07-15 06:38

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>

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>

查看更多
Emotional °昔
3楼-- · 2019-07-15 06:44

You might consider using HttpRequestMessageExtensions.CreateErrorReponse from the System.Net.Http namespace.

There is a discussion of a similar problem here.

查看更多
登录 后发表回答