【问题标题】:Microsoft.AspNetCore.Mvc.Versioning, Version=3.1.0.0 not working in .net core 2.2Microsoft.AspNetCore.Mvc.Versioning,版本 = 3.1.0.0 在 .net 核心 2.2 中不起作用
【发布时间】:2019-12-27 09:48:26
【问题描述】:

我正在尝试在我的核心 api 项目中使用 Microsoft.AspNetCore.Mvc.Versioning, Version=3.1.0.0。

下载了nuget包,下面是我的代码

statup.cs 文件

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        //services.AddApiVersioning();
        services.AddApiVersioning
            (o =>
                {
                    //o.AssumeDefaultVersionWhenUnspecified = true ;
                    //o.DefaultApiVersion = new ApiVersion(new DateTime(2016, 7, 1));
                    o.ReportApiVersions = true;
                    o.AssumeDefaultVersionWhenUnspecified = true;
                    o.DefaultApiVersion = new ApiVersion(1, 0);
                    o.ApiVersionReader = new HeaderApiVersionReader("api-version");
                    o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);
                }
            );
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseApiVersioning();
        app.UseMvc();

    }
}

如下所示的值控制器

[ApiVersion( "2.0" )]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
 }

现在,当我尝试来自 Postman 的获取请求时,我正在获取值。
据我了解,它不应该提供响应,因为我没有为此证明任何标头值。

如果我做错了,请提出建议。

更新 1

当我删除这一行时

 o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);

一切正常。

【问题讨论】:

    标签: c# asp.net-core aspnet-api-versioning


    【解决方案1】:

    API Version Selector

    CurrentImplementationApiVersionSelector 选择最大 API 没有版本状态的可用版本。如果没有匹配 找到后,它会回退到配置的 DefaultApiVersion。 [...]

    如果您不提供调用该特定端点的任何 api 版本,它将找到最大版本(在您的情况下为 2.0)并将其用作默认值。这就是调用该方法的原因。

    [...] 例如,如果版本“1.0”、“2.0”和“3.0-Alpha”是 可用,然后将选择“2.0”,因为它是最高的, 已实现或发布的 API 版本。

    【讨论】:

    • 这是 99% 正确的。它在没有您指定任何标题的情况下工作的原因是因为设置了options.AssumeDefaultVersionWhenUnspecified = true。选择器按照描述解析最大版本。我不确定我们是否有完整的情况,但假设我们有,那么您应该收到 400,因为没有实现 1.0
    猜你喜欢
    • 2018-04-04
    • 2021-04-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多