【问题标题】:Unsupported API version with versions within URI — what's wrong?URI 中的版本不受支持的 API 版本——出了什么问题?
【发布时间】:2019-07-04 23:50:42
【问题描述】:

我有一个使用 .net core 2.2 的 Web API 项目(也许有问题。)

路由正在等待 OpenIdDict 的 OAuth 授权,但这对我来说完全没问题。我正在尝试一种非常简单的方法:

startup.cs 只包含:

services.AddApiVersioning();

API 控制器具有三个不同的路由用于测试目的。请注意,控制器本身没有 [Route()] 或 [ApiVersion()] 注释。

[HttpGet]
[Authorize]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/vt")]
public IActionResult GetVt20()
{
    return Ok("2.0");
}

[HttpGet]
[Authorize]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/vt")]
public IActionResult GetVt10()
{
    return Ok("1.0");
}

如果我提出类似的授权请求

http://localhost:27713/api/v1.0/vt

.net 核心以 BadRequest 回答:

{"error":{"code":"UnsupportedApiVersion","message":"The HTTP resource that matches the request URI 'http://localhost:27713/api/v1.0/vt' does not support the API version '1.0'.","innerError":null}}

我错过了什么?

【问题讨论】:

标签: c# rest .net-core api-versioning


【解决方案1】:

从 2.1 网络核心迁移到 2.2 时,我遇到了同样的问题 只需添加到您的控制器类 [ApiController] 属性

Github Issue

【讨论】:

  • 你说的都是对的。 @Chris Martinez 有隐含的解决方案,而 Lis 指出了具体问题(我都投了赞成票并将 Lis' 设置为解决方案。
【解决方案2】:

您使用的是最新版本的库吗?您使用的是端点路由还是传统路由?您的其余配置是什么样的?由于您提供的信息有限,我看不出它不起作用的直接原因。

这是一个基于您提供的信息的工作示例:

[ApiController]
public class VTController : ControllerBase
{
    [HttpGet]
    [ApiVersion( "1.0" )]
    [Route( "api/v{version:apiVersion}/[controller]" )]
    public IActionResult Get( ApiVersion apiVersion ) =>
        Ok( new { Action = nameof( Get ), Version = apiVersion.ToString() } );

    [HttpGet]
    [ApiVersion( "2.0" )]
    [Route( "api/v{version:apiVersion}/[controller]" )]
    public IActionResult GetV2( ApiVersion apiVersion ) =>
        Ok( new { Action = nameof( GetV2 ), Version = apiVersion.ToString() } );
}

以下路由按预期解析:

  • http://localhost/api/v1/vt
  • http://localhost/api/v2/vt

【讨论】:

  • 你说的都是对的。 @Chris Martinez 有隐含的解决方案,而 Lis 指出了具体问题(我投票赞成并将 Lis' 设置为解决方案。
  • 啊……我明白了。对不起,你踩到了地雷@iquellis。很多人对从版本控制策略中删除 UI 控制器所需的内容并不感到兴奋。没有完美的答案。不幸的是,该解决方案导致某些人出现破坏行为。尽管它在文档和发行说明中被提及,但很容易被忽视。 wiki 还描述了如果您想要旧的行为,如何更改默认规范。
  • 一直没那么重要,想想旧的行为,但还是谢谢。我们在一片绿地上。再次感谢,兄弟。
  • 在添加 [ApiController] 方法后不接受参数。在控制器添加[ApiController]后所有参数为空。
  • @MuhammadSaqib,您必须提供更多上下文或单独的问题。 UI 和 API 控制器之间确实没有区别,但如果您将两者混合使用,[ApiController] 属性可能会导致某些 UI 功能按预期停止工作。
猜你喜欢
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
相关资源
最近更新 更多