.Net Web API throw exception/return response/retur

2019-03-21 18:49发布

问题:

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") });

回答1:

  • 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