Web Api always returns an HTTP 200 status code when an exception occurs

public class GlobalExceptionHandler : ExceptionHandler { public override void Handle(ExceptionHandlerContext context) { context.Result = new NiceInternalServerExceptionResponse("The current operation could not be completed sucessfully.); } } 

When calling this Get action:

  [HttpGet] public async Task<IHttpActionResult> Get() { Convert.ToInt16("this causes an exception state"); var data = await service.Get(); return Ok(data); } 

An exception occurs ... and my global exc handler starts.

When my user response is returned to the client, my violinist always says:

Result: 200

I could also change return Ok(data); on return NotFound();

This will not change anything in the result status code.

How can I rewrite / intercept the creation of the http status and return my own 500 status code?

On my web client, I need to show a nice dialog with an error message id id log + ONLY when returning the status of the code.

+4
source share
3 answers

You need to set the status code to IHttpActionResult :

 public class NiceInternalServerExceptionResponse : IHttpActionResult { public string Message { get; private set; } public HttpStatusCode StatusCode { get; private set; } public NiceInternalServerExceptionResponse( string message, HttpStatusCode code) { Message = message; StatusCode = code; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage(StatusCode); response.Content = new StringContent(Message); return Task.FromResult(response); } } 

And in your GlobalExceptionHandler pass HttpStatusCode.InternalServerError (500):

 public override void Handle(ExceptionHandlerContext context) { context.Result = new NiceInternalServerExceptionResponse( "The current operation could not be completed sucessfully.", HttpStatusCode.InternalServerError); } 
+1
source

I do it like this ...

  [HttpPost] public HttpResponseMessage Post() { try { // Do stuff } catch (Exception ex) { // Something went wrong - Return Status Internal Server Error return new HttpResponseMessage(HttpStatusCode.InternalServerError); } } 

Works the same for Get.

0
source

You can use the following code for custom error:

 return Content(HttpStatusCode.NotFound, "Foo does not exist."); 
0
source

All Articles