Unable to set error message in BadRequest response

Topics: ASP.NET Web API
May 27, 2014 at 6:27 PM
I've run into an issue where my Web API (v 4.0.20710.0) is returning a BadRequest response (using Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Detail.ErrorMessage)) where the response body is simply "Bad Request" regardless of the error message. If I change the status code to Created the appropriate error message is included as expected. The exception being caught is a System.ServiceModel.FaultException<T> and I'm able to inspect the Exception without a problem, but the response body is always just "Bad Request" when I use the BadRequest status code. I've also set the IncludeErrorDetailPolicy config option to IncludeErrorDetailPolicy.Always in Global.asax.cs, and have even tried returning an HttpError and specifying includeErrorDetail, but I get the same odd response.

I'm hoping someone may have run into this before and/or might know what's causing it.
May 27, 2014 at 8:12 PM
This appears to be a result of using Web API in the same project as MVC. We have custom error pages specified in the httpErrors section of system.webServer in Web.config, where errorMode="Custom" and existingResponse="Replace". Removing that section allows the expected response to be returned to the API but breaks the solution we had for custom error pages for the MVC app. I'm assuming the only solution here is to break out the API into it's own application, but I'd be interested to know if there are other alternatives.
Sep 6, 2014 at 12:01 AM
Edited Sep 6, 2014 at 12:02 AM
This is working for me. I still don't know how to trap errors that happen farther up the stack but at least here I can grab them in the JSON response, and still have my pretty MVC custom error pages too.
<configuration>
<!--snip-->
  <system.web>
    <compilation targetFramework="4.5.1" />
    <customErrors mode="On" />
  </system.web>
  <system.webServer>
     <!--snip-->
  </system.webServer>

  <location path="api">
    <system.web>
      <customErrors mode="Off" />
    </system.web>
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false" />
      <httpErrors errorMode="Detailed" existingResponse="PassThrough" >
        <clear/>
      </httpErrors>
    </system.webServer>
  </location>
</configuration>