AssumeDefaultVersionWhenUnspecified无法正常工作

时间:2018-09-25 03:12:48

标签: asp.net-core routing asp.net-core-2.0 asp.net-core-webapi

我一直在为我的WebAPI使用asp net core版本控制组件。需要您的帮助以了解AssumeDefaultVersionWhenUnspecified的工作方式。 (试图搜索文档,但找不到文档)

我的创业公司如下图

services.AddApiVersioning(o => {
            o.ReportApiVersions = true;
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.DefaultApiVersion = new ApiVersion(2, 0);
            o.ApiVersionReader = new UrlSegmentApiVersionReader();
        });

当route属性如下所示时

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/values")]
[ApiController]
public class ValuesV2Controller : ControllerBase
{
...
}

仅当指定了api版本时,以上路由才有效。即:http://localhost:55401/api/v2/values 如果我像http://localhost:55401/api/values这样打来电话,就会收到404错误

我的问题是这个... AssumeDefaultVersionWhenUnspecified如何工作。它不会忽略Route中的版本吗?看起来Route属性优先于AssumeDefaultVersionWhenUnspecified。如果我选择QueryString或Header版本控制,并且当路由看起来像

[ApiVersion("2.0")]
[Route("api/values")]

默认路由到达API

我错过了什么吗?还是我的理解错了?如何使用url版本控制实现默认路由到最新版本的API?

3 个答案:

答案 0 :(得分:1)

简而言之,我的理解是错误的。感谢克里斯的澄清。您可能会从https://github.com/Microsoft/aspnet-api-versioning/issues/351#issuecomment-425106940

获得更多信息

答案 1 :(得分:0)

Summarizing the the solution from the github issue linked by Athi S, here's what you need to do :

In ConfigureServices inside Startup.cs file :

        services.AddApiVersioning(o =>
        {
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);
            //  o.DefaultApiVersion = new ApiVersion(1, 0);
        });

You can optionally set ApiVersionSelector to a new instance of CurrentImplementationApiVersionSelector. What this does is, it automatically selects the highest api version registered in controllers. E.g. A controller decorated with [ApiVersion("1.2")] takes precedence over [ApiVersion("1.1")].

If you want to specify default api version explicitly, you can do so by leaving ApiVersionSelector to DefaultApiVersionSelector and setting DefaultApiVersion to your required api version.

In your controllers :

Register the required routes by decorating your controllers with the given Route attributes

[Route("api/[controller]")]

Or if you want the api to work both with and without the api version number specified, you can do so by declaring two routes for the controller.

[Route("api/[controller]")]
[Route("api/v{version:apiVersion}/[controller]")]

答案 2 :(得分:0)

我也在尝试实现相同的功能。通过查看[https://github.com/Microsoft/aspnet-api-versioning/issues/351#issuecomment-425106940] 我假设我们无法通过仅使用URL段AssumeDefaultVersionWhenUnspecified

的单一样式来实现默认的API版本[Route("api/v{version:apiVersion}/[controller]")]功能。

我们必须分别定义两条路线

  1. [Route("api/[controller]")]
  2. [Route("api/v{version:apiVersion}/[controller]")]

并要掩盖这两种实现,您可以使用此link