C# 无法使Api版本在Web Api C中工作#
我试图使用在一个流行的在线站点上找到的教程来版本我的api调用。我无法让路由正常工作。我设置了两个控制器,版本1和版本2,但我总是被路由到版本2。值得一提的是,我在教程中找到的代码似乎也有同样的问题 控制器1:C# 无法使Api版本在Web Api C中工作#,c#,asp.net,asp.net-web-api2,C#,Asp.net,Asp.net Web Api2,我试图使用在一个流行的在线站点上找到的教程来版本我的api调用。我无法让路由正常工作。我设置了两个控制器,版本1和版本2,但我总是被路由到版本2。值得一提的是,我在教程中找到的代码似乎也有同样的问题 控制器1: using System.Collections.Generic; using System.Web.Http; using Microsoft.Web.Http; namespace WebDemoAPI.Controllers { [ApiVersion("1.0")]
using System.Collections.Generic;
using System.Web.Http;
using Microsoft.Web.Http;
namespace WebDemoAPI.Controllers
{
[ApiVersion("1.0")]
[Route("api/values")]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
//throw new NotImplementedException("");
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id){return "value";}
// POST api/values
public void Post([FromBody]string value) { }
// PUT api/values/5
public void Put(int id, [FromBody]string value) { }
// DELETE api/values/5
public void Delete(int id) { }
}
}
我尝试将标题键设置为version,值设置为1.0,但我被路由到2.0版本的控制器。将标题值设置为2.0有效。保留标题键/值也会路由到控制器2 在
Microsoft.Web.Http.Versioning
命名空间中有4个预定义的版本选择器:
CurrentImplementationApiVersionSelector
如果请求中未指定任何api版本,则选择最新的api版本。LowestImplementedAPI版本选择器
如果请求中未指定任何api版本,则选择最低的api版本。ConstantAversionSelector
如果请求中没有指定,则选择传入构造函数的常量api版本。DefaultApiVersionSelector
如果请求中未指定任何选项,则在apiversionoptions
中选择DefaultApiVersion
因此,如果希望默认情况下选择DefaultApiVersion
,则需要使用DefaultApiVersionSelector
//or just remove this line since this is a default selector
ver.ApiVersionSelector = new DefaultApiVersionSelector(ver);
如果版本控制仍然不起作用,您可能以错误的方式设置了Version
标题值或其他内容。您还可以检查它是否与其他版本读取器一起工作,例如QueryStringApiVersionReader
。更新配置
ver.ApiVersionReader = new QueryStringApiVersionReader("version");
并在查询字符串中传递版本
/api/values?version=1
如何测试对该API的调用?这看起来有点问题,因为
CurrentImplementationApiVersionSelector
总是接管并路由到API的2.0版。@TimoSalomäki使用Postman进行测试。你是说我应该删除文件中的属性设置吗?我刚刚复制了你的配置,当我在Postman中将Version
header设置为1
时,一切正常。问题仍然存在吗?@Alexander是的,它仍然存在。@Alexander你会发布你从邮递员那里使用的URI吗?这是一个漫长的过程,但也许我没有关注这一部分。否则,我就不知所措了。
ver.ApiVersionReader = new QueryStringApiVersionReader("version");
/api/values?version=1