简体   繁体   English

.NET Web API BadRequest() 方法是否等同于 Request.CreateErrorResponse(…)

[英]Is the .NET Web API BadRequest() method equivalent to Request.CreateErrorResponse(…)

In our Web API at my company, we currently return our 400 error responses with the code:在我公司的 Web API 中,我们目前返回带有代码的 400 错误响应:

return request.CreateErrorResponse(HttpStatusCode.BadRequest, someErrorMessage);

However, in my personal projects with Web API and in some of the documentation, I have seen the much cleaner code for returning various status codes, such as:但是,在我使用 Web API 的个人项目中以及在一些文档中,我看到了用于返回各种状态代码的更简洁的代码,例如:

return BadRequest(someErrorMessage);

What's the difference between these two methods of returning a 400 response?这两种返回 400 响应的方法有什么区别? Which is preferred?哪个是首选? Can we safely migrate from one variant to another without any difference in what the consumer of the API will see?我们能否安全地从一种变体迁移到另一种变体,而 API 的消费者会看到什么? We use Swagger, if that makes a difference.我们使用 Swagger,如果有区别的话。

They are just different ways from different libraries for creating response messages and there is no different in the generated response.它们只是来自不同库用于创建响应消息的不同方式,并且生成的响应没有什么不同。

In the code i suggest using ApiController built in methods like BadRequest(), InternalServerError() and Ok().在代码中,我建议使用内置方法的 ApiController,例如 BadRequest()、InternalServerError() 和 Ok()。

But Some http status codes is not available in ApiController methods like "406 Not Acceptable", "426 Upgrade Required" and etc, so you have to use another way like CreateErrorResponse() method Or you can extend ApiController and create your own methods for generating error responses that more used in your application.但是某些 http 状态代码在 ApiController 方法中不可用,例如“406 Not Acceptable”、“426 Upgrade required”等,因此您必须使用另一种方式,例如 CreateErrorResponse() 方法或者您可以扩展 ApiController 并创建自己的生成方法在您的应用程序中更多使用的错误响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM