4

版本 WebAPI 的最佳方法是什么?

我正在从头开始构建一个 API,我想确保它在未来能够优雅地进行版本化。我正在设想类似 mysite.com/api/v2/...

我看到的一种方法是为每个 API 版本创建一个单独的项目(网络应用程序)。但也许有更好的方法来做到这一点?

谢谢你的想法。

4

2 回答 2

4

Including version number in the URL is the standard approach as I explained in this post (I do not repeat the content): Implementing versioning a RESTful API with WCF or ASP.Net Web Api

You do not need to create a completely new project although you can. The problem that you will be facing with a single project is that there will be collision of names:

/api/v1.0/Car/123

and

/api/v2.0/Car/123

both will point to CarController while you can have only one of those. The solution would be to implement your own IHttpControllerSelector and register with the DependencyResolver. This implementation will look at the version number and perhaps find the type based on the namespace.


UPDATE

I do not intend to start a REST controversy here. But as @DarrelMiller points out, here is an older discussion on the same subject discouraging my suggested approach:

How to version REST URIs

I personally think URL versioning is the way to go.

于 2012-05-23T08:24:20.480 回答
3

您将需要创建自己的IHttpControllerSelector. 最好的方法是将此实现基于 Microsoft 的IHttpControllerSelector. 然后,您可以决定是IHttpControllerSelector要按 URL 还是按内容类型进行版本控制。

最基本的实现直接实现IHttpControllerSelector并且只是实现该SelectController方法,但出于性能原因,最好围绕它实现一些缓存。

为了找到控制器,您IHttpControllerTypeResolver可以简单地使用可以使用的实例HttpConfiguration.Services

我用过这样的东西:http: //damsteen.nl/blog/implementing-versioning-in-asp.net-web-api。还要在 Github 上放一些代码:https ://github.com/Sebazzz/SDammann.WebApi.Versioning 。

于 2012-08-01T14:46:21.813 回答