c# - 是否可以对 ASP.NET Core Controller 中的特定方法使用 API 版本控制?

标签 c# asp.net-core

我正在使用 Microsoft.AspNetCore.Mvc.Versioning (v4.1) 提供的 API 版本控制方法。 所以在启动类中我有以下内容:

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllers();

  services.AddMvc(options => options.Filters.Add<ExceptionFilter>());

  services.AddApiVersioning(options =>
  {
      options.ApiVersionReader = new MyCustomVersionReader(configuration);
      options.AssumeDefaultVersionWhenUnspecified = false;
      options.ReportApiVersions = true;
      options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
  });            
}

在 Controller 中,我可以将注释 [ApiVersion("1.0")] 添加到 Controller 或单个方法。

[HttpGet]
[ApiVersion("1.0")]
public async Task<IActionResult> Get() {...}

使用此功能,对 api 的所有调用都必须在请求 header 中包含版本信息。

但是,是否可以在 Controller 中使用不需要版本的特定方法?

例如

[HttpGet]
[ApiVersion("1.0")]
public async Task<IActionResult> Method1() {...} //requires version in header

[HttpGet]
public async Task<IActionResult> Method2() {...} //does not require version in header

当我尝试上述操作(省略 Method2 的 ApiVersion 注释)时,我仍然收到以下错误:

“需要 API 版本,但未指定。”

感谢您的帮助!

最佳答案

我认为您可以使用[ApiVersionNeutral]属性。您可以在下面看到我的演示。

首先在启动中添加:

 options.Conventions.Controller<HomeV1Controller>().HasApiVersion(new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0));

然后在您的HomeV1Controller中:

[Route("api/[controller]")]
[ApiController]
public class HomeV1Controller : ControllerBase
{
    [HttpGet("get")]
    public string Get() => "Ok1";

    [HttpGet("getv2")]
    [ApiVersionNeutral]
    public string GetV2() => "Ok2";
}

测试结果: enter image description here

关于c# - 是否可以对 ASP.NET Core Controller 中的特定方法使用 API 版本控制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65774716/

相关文章:

c# - File.WriteAllBytes 在映射网络驱动器上完成后的文件大小

c# - WebBrowser 控件的安全级别

c# - 如何将 LINQ 支持添加到我的库中?

c# - XML 序列化 : is Order mandatory on your class when you specifiy at least 1 Order attribute?

configuration - 如何在ASP.NET vNext中允许MIME扩展名映射?

c# - 如果 user.config 中有 Int32[] 属性,我在使用 CustomSettingsProvider 时会收到无效的转换异常

.net - 保护 Azure 上的 .NET Core API - 仍然接受设置了 RequireHttpsAttribute 的 HTTP

c# - 使用将 net461 设置为唯一框架的 ASP.NET Core Web 应用程序 (.NET Core) 与使用 (.NET Framework) 模板之间的区别

c# - 如何升级 azure CI 以使用 c# 8.0

重定向后未加载 JavaScript 文件?