NSwag:从多个API版本

时间:2018-05-30 11:56:50

标签: c# swagger swashbuckle autorest nswag

我们正在使用ASP.NET Core 1.1中的Swashbuckle对API进行版本控制并生成Swagger规范。我们可以根据这些JSON规范文件生成两个API文档:

<!-- language: c# -->
services.AddSwaggerGen(setupAction =>
{
    setupAction.SwaggerDoc("0.1", new Info { Title = "Api", Version = "0.1", Description = "API v0.1" });
    setupAction.SwaggerDoc("0.2", new Info { Title = "Api", Version = "0.2", Description = "API v0.2" });

    // more configuration omitted
}

我们将两个规范文件中的所有操作都包括在内,除非使用[MapToApiVersion]ApiExplorerSettings(GroupName ="<version>")]属性将其映射到特定版本。仅属于旧版本的方法也使用[Obsolete]属性进行修饰:

<!-- language: c# -->
[MapToApiVersion("0.1")]
[ApiExplorerSettings(GroupName = "0.1")]
[Obsolete]

但是,我们希望只有一个C#客户端从两个规范文件的Union生成,其中所有方法都包含在Client中,0.1和0.2,但所有过时的方法实际上都标记为过时。< / p>

我已经研究了NSwag(我们现在使用了很长时间)以及AutoRest。 AutoRest似乎support a merging scenario,但由于模式验证错误,我无法使其工作(我不确定我们的具体方案是否真的得到支持)。

到目前为止我的最后一个想法是将JSON合并为一个,然后将其提供给NSwag。

我们在这里错过了吗?用NSwag可以实现这种方式吗?

3 个答案:

答案 0 :(得分:3)

我写了一篇关于类似问题https://medium.com/dev-genius/nswag-charp-client-from-multiple-api-versions-7c79a3de4622

的文章

首先,创建一个架构。如我所见,有两种方法:

  • 存在多个版本的一个架构
  • 每个版本的
  • 自己的模式

接下来,为每个受支持的版本创建客户端,并将其包装在包装客户端下:

public class AppApiClient
{
    public IV1Client V1 { get; }
    public IV2Client V2 { get; }

    public AppApiClient(HttpClient httpClient)
    {
        V1 = new V1Client(httpClient);
        V2 = new V2Client(httpClient);
    }
}

答案 1 :(得分:0)

这是我的想法,从评论中扩展:

使用swashbuckle,您可以根据需要生成尽可能多的SwaggerDoc,这个案例的想法是生成3保持相同的2个版本,并添加一个将拥有一切。

c.MultipleApiVersions(
    (apiDesc, targetApiVersion) => 
      targetApiVersion.Equals("default") || // Include everything by default
      apiDesc.Route.RouteTemplate.StartsWith(targetApiVersion), // Only include matching routes for other versions
    (vc) =>
    {
        vc.Version("default", "Swagger_Test");
        vc.Version("v1_0", "Swagger_Test V1_0");
        vc.Version("v2_0", "Swagger_Test V2_0");
    });

这是一个工作样本:
http://swagger-net-test-multiapiversions.azurewebsites.net/swagger/ui/index?filter=Api

该项目的整个代码都在GitHub上:
https://github.com/heldersepu/Swagger-Net-Test/tree/MultiApiVersions

答案 2 :(得分:0)

包装:

安装软件包Swashbuckle.AspNetCore

安装软件包Microsoft.AspNetCore.Mvc.Versioning

enter image description here

ValueV1Controller.cs

[ApiVersion("1")]
[Route("api/v{version:apiVersion}/Values")]
public class ValuesV1Controller : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

ValueV2Controller.cs

[ApiVersion("2")]
[Route("api/v{version:apiVersion}/Values")]
public class ValuesV2Controller : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1.2", "value2.2" };
    }
}

Startup.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();
        services.AddApiVersioning();
        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API - V1", Version = "v1" });
            c.SwaggerDoc("v2", new Info { Title = "My API - V2", Version = "v2" });

            c.DocInclusionPredicate((docName, apiDesc) =>
            {
                var versions = apiDesc.ControllerAttributes()
                    .OfType<ApiVersionAttribute>()
                    .SelectMany(attr => attr.Versions);

                return versions.Any(v => $"v{v.ToString()}" == docName);
            });

            c.OperationFilter<RemoveVersionParameters>();
            c.DocumentFilter<SetVersionInPaths>();
        });
    }

    // 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();
        }

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });

        app.UseMvc();
    }
}

public class RemoveVersionParameters : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var versionParameter = operation.Parameters?.SingleOrDefault(p => p.Name == "version");
        if (versionParameter != null)
            operation.Parameters.Remove(versionParameter);
    }
}

public class SetVersionInPaths : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Paths = swaggerDoc.Paths
            .ToDictionary(
                path => path.Key.Replace("v{version}", swaggerDoc.Info.Version),
                path => path.Value
            );
    }
}