问题描述
我想在一个REST API,那里的版本是在标题中指定,如API版本启用版本:2
I am trying to enable versioning on a REST API, where the version is specified in the header, as "api-version":2
.
据this教程我只需要创建
VersionConstraint:IHttpRouteConstraint
和
VersionedRoute:RouteFactoryAttribute
的使用将是适用 [VersionedRoute(API / controllerName,2)]
属性到控制器,它是专为特定版本(比如2版本这种情况下)。
The usage would be to apply the [VersionedRoute("api/controllerName", 2)]
Attribute to Controllers, which are designed for specific versions (e.g. version 2 in this case).
这是所有好,很好,但不幸的是,这一切都在MVC5和我使用MVC6。因此, RouteFactoryAttribute
和 IHttpRouteConstraint
不起作用。
This is all good and well, but unfortunately, it's all in MVC5 and I'm using MVC6. Therefore, RouteFactoryAttribute
and IHttpRouteConstraint
don't work.
我设法找到 IRouteConstraint
来代替 IHttpRouteConstraint
(希望这将工作),但我不能找到一个替代为 RouteFactoryAttribute
。
I managed to find IRouteConstraint
to replace IHttpRouteConstraint
(hoping it will work), but I cannot find a replacement for RouteFactoryAttribute
.
如果任何人都可以提供样品本使用MVC 6,或至少提正确的类(最好有命名空间),我需要继承?
If anyone can provide a sample of this using MVC 6, or at least mention the correct classes (ideally with namespaces) I need to inherit from?
推荐答案
下面是你需要工作的最低金额。
Here's the minimum amount of work you need.
首先,请并复制在code为3以下文件:
First, go there and copy the code for the 3 following files:
一旦你有了这个,我们会改变 VersionRangeValidator
的 GetVersion
方法如下:
Once you have this, we'll change the GetVersion
method of VersionRangeValidator
for the following:
public static string GetVersion(HttpRequest request)
{
if (!string.IsNullOrWhiteSpace(request.Headers["api-version"]))
return request.Headers["api-version"];
return "1";
}
这将读取头,并返回API版本。默认为 V1
在这种情况下。
That will read the header and return the API version. The default will be v1
in this scenario.
下面是如何使用它的控制器(也可以是2个动作相同的控制器:
Here's how to use it on controllers (or it can be the same controllers with 2 actions:
[Route("api/data")]
public class DataController
{
[VersionGet("", versionRange: "[1]")]
public string GetData()
{
return "v1 data";
}
}
[Route("api/data")]
public class DataV2Controller
{
[VersionGet("", versionRange: "[2]")]
public string GetData()
{
return "v2 data";
}
}
所以,现在你只需要给它的右侧头和它的好。这code已被使用jQuery测试是这样的:
So now you just need to give it the right header and it's good. This code has been tested with jQuery like this:
$(document).ready(function(){
$.ajax({url: '/api/Data/', headers: { 'api-version': 1 }})
.then(function(data){
alert(data);
});
$.ajax({url: '/api/Data/', headers: { 'api-version': 2 }})
.then(function(data){
alert(data);
});
});
这篇关于VersionedRoute属性为MVC6实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!