使用Microsoft.AspNetCore.Mvc.Versioning,Swashbuckle.AspNetCore和MaptoApiVersion

时间:2017-05-25 18:00:14

标签: asp.net-core swagger swashbuckle

我在使用MapToApiVersion时遇到问题。从http://localhost:5000/swagger开始,1.0 Docs和2.0 Docs正确地呈现了swagger ui,并且相应的swagger.json文件可用。 3.0 Docs无法渲染,并且似乎没有生成swagger.json文件。

对于所有3个版本,实际服务已正常运行。如果我从邮递员那里得到它,我得到了我期望的响应。

这是运行Mvc.Versioning的1.1.1-rc1和Swashbuckle.AspNetCore的1.0.0。完整的.csproj

https://github.com/senften/AspNetCoreVersionedWebApi/tree/maptoapiversion

的完整代码

当我在Visual Studio Code中的调试中运行它时,我没有看到任何错误或有任何异常。我搞砸了启动或声明,还是我只是遇到了垫片或者虚假的错误?

using Microsoft.AspNetCore.Mvc;
using VersionedWebApi.Model;

namespace VersionedWebApi.Controllers
{
    /// <summary>
    /// GoodByeController, just saying Goodbye!
    /// </summary>
    [ApiVersion("1.0", Deprecated = true)]
    [ApiVersion("3.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    public class GoodByeController : Controller
    {
        /// <summary>
        /// Default Get call returning Goodbye world!
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(GoodByeWorldModel), 200)]
        [ProducesResponseType(typeof(void), 404)]
        public GoodByeWorldModel Get()
        {
            return new GoodByeWorldModel();
        }

        /// <summary>
        /// Default Get call returning Goodbye world!
        /// </summary>
        /// <returns></returns>
        [HttpGet, MapToApiVersion("3.0")]
        [ProducesResponseType(typeof(VersionedWebApi.Model.v3.GoodByeWorldModel), 200)]
        [ProducesResponseType(typeof(void), 404)]
        public VersionedWebApi.Model.v3.GoodByeWorldModel GetV3()
        {
            return new VersionedWebApi.Model.v3.GoodByeWorldModel();
        }
    }
}

startup.cs

using System.Xml.XPath;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SwashbuckleAspNetVersioningShim;

namespace VersionedWebApi
{
    public class Startup
    {
        public Startup()
        {
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            var mvcBuilder = services.AddMvc();
            services.AddMvcCore().AddVersionedApiExplorer();

            // Adds versioning capabilities, defaulting to version 1.0 calls if available
            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });

            // Add generated documentation
            services.AddSwaggerGen(c =>
            {
                var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
                SwaggerVersioner.ConfigureSwaggerVersions(c, provider);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ApplicationPartManager partManager, IApiVersionDescriptionProvider provider)
        {
            // Generate swagger.json
            app.UseSwagger();

            // Let's enable SwaggerUI
            app.UseSwaggerUI(c =>
            {
                SwaggerVersioner.ConfigureSwaggerVersions(c, provider);
            });

            app.UseMvc();
            // This is new for v1.1 and is a behavioral breaking change from previous (including 1.1-beta)
            // See the release notes: https://github.com/Microsoft/aspnet-api-versioning/releases/tag/v1.1-rc1
            app.UseApiVersioning();
        }
    }
}

csproj文件

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <Company />
    <Description>A .NET Core Web API project demonstrating versioning a Web API and generating interactive documentation with Swagger.</Description>
    <RepositoryUrl>https://github.com/senften/AspNetCoreVersionedWebApi</RepositoryUrl>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile></DocumentationFile>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.1.0-rc1"/>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />
    <PackageReference Include="SwashbuckleAspNetVersioningShim" Version="1.0.0-beta4"/>
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0"/>
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="*"/>
  </ItemGroup>

</Project>

2 个答案:

答案 0 :(得分:0)

需要对代码进行一些更改。

1)将以下代码更改为

    [ApiVersion("3.0"), Route("api/v{api-version:apiVersion}/[controller]")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    public class HelloController : Controller
    { }


    [ApiVersion("3.0"), Route("api/v{api-version:apiVersion}/[controller]")]
    public class HelloController : Controller
    { }

2)添加MapToApiVersion 1.0以避免冲突

[HttpGet, MapToApiVersion("1.0")]
[ProducesResponseType(typeof(GoodByeWorldModel), 200)]
[ProducesResponseType(typeof(void), 404)]
public GoodByeWorldModel Get()
{
    return new GoodByeWorldModel();
}

答案 1 :(得分:0)

您遇到的问题是填充库的行为。

当生成Swagger文档时,控制器上指定的ApiVersion将应用于其中未明确设置为其他内容的所有方法。 在这种情况下,因为MapToApiVersion方法上没有Get()属性,它会被添加到V1和V3 Swagger文档中,因为这是控制器上指定的内容。这会在生成Swagger文档时导致过载错误。

好消息是这是一个简单的修复方法,只需将[HttpGet, MapToApiVersion("1.0")]添加到您的Get()方法中就可以看起来像这样

/// <summary>
/// Default Get call returning Goodbye world!
/// </summary>
/// <returns></returns>
[HttpGet, MapToApiVersion("1.0")]
[ProducesResponseType(typeof(GoodByeWorldModel), 200)]
[ProducesResponseType(typeof(void), 404)]
public GoodByeWorldModel Get()
{
    return new GoodByeWorldModel();
}

Get()方法只会添加到V1文档中,其余代码可以保持原样。

关于Shim的GitHub Readme有关此行为的更多细节