的.NET Web API抛出异常/返回四百分之四百零四响应响应/返回错误的反应? [英] .Net Web API throw exception/return response/return error response for 404/400 response?
问题描述
我使用的.NET Web API开发一些RESTful Web服务。
我需要返回404(NotFoundStatus)或400(错误请求)的客户端的一些场景。
好像有许多方式中的框架来做到这一点。下面列出一些我知道的方式。
有选择使用,返回这些响应其中之一的指引?
返回Request.CreateErrorResponse(的HTTPStatus code.NotFound,错误); 返回Request.CreateResponse(的HTTPStatus code.NotFound,错误); 抛出新的Htt presponseException(新的Htt presponseMessage(的HTTPStatus code.NotFound){内容=新的StringContent(错误)});
-
的
CreateErrorResposne
扩展创建的内容协商的答复,但它也有多少应该出现此错误信息是逻辑发回给客户机。我们的想法是不透露太多的信息给客户端,它可能是一个安全问题。例如,httpConfig.IncludeErrorDetailPolicy
确定多少信息被发送回客户端。 -
上面的
CreateResponse
扩展也为创建的内容协商的反应,但它的不的有什么是我上面提到的CreateErrorResponse
额外的逻辑。 -
在第三种情况,响应的不的内容协商和你总是在
文本发回的内容/纯
格式,同时它的不的有额外的逻辑在CreateErrorResposne
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") });
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 forCreateErrorResponse
.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 inCreateErrorResposne
这篇关于的.NET Web API抛出异常/返回四百分之四百零四响应响应/返回错误的反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!