Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Web API throw exception/return response/return error response for 404/400 response?

I am developing some restful web service using .net web api.

I need to return 404 (NotFoundStatus) or 400 (BadRequest) to the client for some scenarios.

It seems like that there are many ways to do this in the framework. Following list some of the ways that I know about.

Is there any guideline of choosing which one to use for returning these response?

        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Error");

        return Request.CreateResponse(HttpStatusCode.NotFound, "Error");

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Error") });
like image 388
Stay Foolish Avatar asked Nov 24 '25 01:11

Stay Foolish


1 Answers

  • The CreateErrorResposne extension is for creating content-negotiated responses but it also has logic of how much of this error information should be sent back to the client. The idea is to not reveal too much of information to the client which could be a security issue. For example, httpConfig.IncludeErrorDetailPolicy determines how much information is sent back to the client.

  • The CreateResponse extension above is also for creating content-negotiated responses, but it does not have any of the additional logic that I mentioned above for CreateErrorResponse.

  • In the third scenario, the response is not content-negotiated and you would be sending back content always in text/plain format and also it does not have additional logic as in CreateErrorResposne

like image 89
Kiran Avatar answered Nov 27 '25 00:11

Kiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!