Swashbuckle 扩展版本开关

Swashbuckle extension version switch

我是 asp.net 核心的新手,我正在使用 swagger。我按照以下步骤下载了它 Install-Package Swashbuckle.AspNetCore -Version 5.6.3.Then add middleware

services.AddSwaggerGen();Then add  app.UseSwagger(c =>
    {
        c.SerializeAsV2 = true;
    });

    
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    }); to the ge

nerated JSON 文档和 Swagger UI。

最后按照文档添加头信息。

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "A simple example ASP.NET Core Web API",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = new Uri("https://twitter.com/spboyer"),
        },
        License = new OpenApiLicense
        {
            Name = "Use under LICX",
            Url = new Uri("https://example.com/license"),
        }
    });
});

这些都是遵循文档的要求。但是我现在需要扩展需求,需要添加API的版本信息,类似API V1 API V2版本开关。我参考了一些资源,但没有完整的代码,你们能帮帮我吗?任何帮助都很棒! !

您是否尝试像这样切换版本?

首先我创建了2个版本的文件夹和controllers.Therefore,每个控制器的命名空间对应它的文件夹,像这样:

V1版本:

namespace WebApplication129.Controllers.V1
{
    [ApiController]
    [Route("api/v1/[controller]")]
    public class HomeController : ControllerBase
    {

       [Route("test")]
        [HttpGet]
        public string Test()
        {
            return "v1 test";
        }
    }
}

V2版本:

namespace WebApplication129.Controllers.V2
{
    [ApiController]
    [Route("api/v2/[controller]")]
    public class HomeController : ControllerBase
    {

        [Route("test")]
        [HttpGet]
        public string Test()
        {
            return "v2 test";
        }
    }
}

然后创建一个协议通知Swagger,这样我们就可以控制Swagger如何生成Swagger文档,从而控制UI.

创建以下 class:

public class GroupingByNamespaceConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        var controllerNamespace = controller.ControllerType.Namespace;
        var apiVersion = controllerNamespace.Split(".").Last().ToLower();
        if (!apiVersion.StartsWith("v")) { apiVersion = "v1"; }
        controller.ApiExplorer.GroupName = apiVersion;
    }
}

现在我们必须应用约定。为此,我们转到 ConfigureServices 中的 AddControllers 并添加约定:

services.AddControllers(options =>
{
    options.Conventions.Add(new GroupingByNamespaceConvention());
});

最终完成的startup.cs配置如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using WebApplication129.Controllers.conf;

namespace WebApplication129
{
    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.AddControllers(options =>
            {
                options.Conventions.Add(new GroupingByNamespaceConvention());
            });

            services.AddSwaggerGen(config =>
            {
                var titleBase = "Test API";
                var description = "This is a Web API for Test operations";
                var TermsOfService = new Uri("https://xxxxxx");
                var License = new OpenApiLicense()
                {
                    Name = "Test"
                };
                var Contact = new OpenApiContact()
                {
                    Name = "Test",
                    Email = "Test@hotmail.com",
                    Url = new Uri("https://xxxxxx")
                };

                config.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = titleBase + " v1",
                    Description = description,
                    TermsOfService = TermsOfService,
                    License = License,
                    Contact = Contact
                });

                config.SwaggerDoc("v2", new OpenApiInfo
                {
                    Version = "v2",
                    Title = titleBase + " v2",
                    Description = description,
                    TermsOfService = TermsOfService,
                    License = License,
                    Contact = Contact
                });
            });
        }

       
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(config =>
            {
                config.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
                config.SwaggerEndpoint("/swagger/v2/swagger.json", "API v2");
            });
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}