I'm trying to return custom error responses from web.api. Let it be simple string "Oops!"
formatted as json. So I created simple delegating handler which replaces error responses like this:
public class ErrorMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.IsSuccessStatusCode)
return response;
var formatter = new JsonMediaTypeFormatter();
var errorResponse = request.CreateResponse(response.StatusCode, "Oops!", formatter);
return errorResponse;
}
}
Next I make sure that this is the only one message handler in pipeline:
httpConfig.MessageHandlers.Clear();
httpConfig.MessageHandlers.Add(new ErrorMessageHandler());
// Only default route
httpConfig.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(httpConfig); // OWIN self-hosting
Controller is also simplest one:
public class ValuesController : ApiController
{
public IHttpActionResult Get(int id)
{
if (id == 42)
return Ok("Answer to the Ultimate Question of Life, the Universe, and Everything");
return NotFound();
}
}
And here goes interesting:
/api/values/42
gives me 200 response with value string/api/values/13
gives me 404 response with my custom"Oops!"
string/api/values/42/missing
gives me empty 404 response
The last case is my problem. When I set a breakpoint on the last line of delegating handler I clearly see that errorResponse
contains ObjectContent<string>
with the correct value. But why this value is cleared away later?