【问题标题】:ASP.NET Core API versionASP.NET Core API 版本
【发布时间】:2021-03-14 20:26:28
【问题描述】:

我正在尝试使用 ASP.NET Core 及其版本创建 API。我安装了Microsoft.AspNetCore.Mvc.Versioning。我喜欢的是所有在 URL 中带有版本的 API,所以很容易理解我使用的是什么版本的 API。例如/api/v1/TableAzureCategory

为此,我在Startup.cs 中添加了以下代码行:

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

然后,我在我的 API 控制器中添加了一些装饰

[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class TableAzureCategoryController : ControllerBase
{
}

我运行应用程序,打开 Swagger,这就是我所看到的(基本上 {version:apiVersion} 不会被 API 版本替换)

我环顾四周,但我发现只有我上面的实现。有什么想法吗?

【问题讨论】:

  • 你必须大摇大摆地告诉它。我忘记了它叫什么,“分组”的东西。但是有两个选项来设置,然后基本上是一个 foreach 循环来调用 API 版本描述符(或类似的东西)。不记得我脑海中的细节,但希望这能帮助你找到一些谷歌搜索
  • 其实,给你:medium.com/@hendisuhardja/…

标签: c# asp.net-core asp.net-core-webapi asp.net-routing


【解决方案1】:

实现此目的的另一种方法是创建基于查询的版本控制解决方案。

假设我们有两个控制器:ExampleV1Controller 和 ExampleV2Controller

using Microsoft.AspNetCore.Mvc;

namespace MyAPI.Controllers
{
    [ApiController]  
    [ApiVersion("1.0")]  
    [Route("api/example")]
    public class ExampleV1Controller : ControllerBase  
    {
        [HttpGet]  
        public IActionResult Get()  
        {  
            return new OkObjectResult("Example API v1");  
        }
    }

    [ApiController]  
    [ApiVersion("2.0")]  
    [Route("api/example")]
    public class ExampleV2Controller : ControllerBase  
    {
        [HttpGet]  
        public IActionResult Get()  
        {  
            return new OkObjectResult("Example API v2");  
        }
    }
}

根据您的 Startup.cs 配置,它将默认为 API 版本 1.0。要向 V2 版本发出请求,请使用 https://localhost:5001/api/example?api-version=2.0

我自己没有对此进行测试,但它应该可以工作。

【讨论】:

  • 是的,谢谢,我看到了,但在我看来,url 中的版本更优雅。
【解决方案2】:

{version} 路由参数的行为与任何其他路由参数一样。如果路由是values/{id}/subvalues,您会期望一个名为id 的参数必须填写。

API 版本控制的 API Explorer 扩展知道与 API 关联的版本。此值用作默认值,但 OpenAPI/Swagger 生成器(例如:Swashbuckle)在没有一点帮助的情况下可能不会使用默认值(请参阅端到端Swagger Example)。当且仅当您按 URL 段进行版本控制时,您可以让 API Explorer 扩展使用默认值扩展路由模板,并使用配置删除 API 版本参数:

services.AddVersionedApiExplorer(options => options.SubstituteApiVersionInUrl = true);

在提供的示例中,version 路由参数将被删除,路由模板将更新为 "api/v1.0/TableAzureCategory",我想这就是您想要的。

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 2019-08-20
    • 2021-06-19
    • 2020-07-08
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多