c# - 如何设置 Swashbuckle 与 Microsoft.AspNetCore.Mvc.Versioning

标签 c# asp.net-core swagger swashbuckle

我们有asp.net core webapi。我们添加了 Microsoft.AspNetCore.Mvc.Versioning 和 Swashbuckle 以获得 swagger UI。 我们将 Controller 指定为:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ContactController : Controller
{

当我们运行 swagger ui 时,我们将版本作为路由中的参数: enter image description here

如何为路由设置默认“v1”? 如果版本 2 出现,如何支持两个版本的 swagger ui?

最佳答案

目前 Swashbuckle 和 Microsoft.AspNetCore.Mvc.Versioning 是 friend 。效果很好。我刚刚在 VS2017 中创建了测试项目并检查了它是如何工作的。

首先包含这两个nuget包:

<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.2.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />

Startup.cs 中配置所有内容(阅读我的评论):

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


        // Configure versions 
        services.AddApiVersioning(o =>
        {
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.DefaultApiVersion = new ApiVersion(1, 0);
        });

        // Configure swagger
        services.AddSwaggerGen(options =>
        {
            // Specify two versions 
            options.SwaggerDoc("v1", 
                new Info()
                {
                    Version = "v1",
                    Title = "v1 API",
                    Description = "v1 API Description",
                    TermsOfService = "Terms of usage v1"
                });

            options.SwaggerDoc("v2",
                new Info()
                {
                    Version = "v2",
                    Title = "v2 API",
                    Description = "v2 API Description",
                    TermsOfService = "Terms of usage v2"
                });

            // This call remove version from parameter, without it we will have version as parameter 
            // for all endpoints in swagger UI
            options.OperationFilter<RemoveVersionFromParameter>();

            // This make replacement of v{version:apiVersion} to real version of corresponding swagger doc.
            options.DocumentFilter<ReplaceVersionWithExactValueInPath>();

            // This on used to exclude endpoint mapped to not specified in swagger version.
            // In this particular example we exclude 'GET /api/v2/Values/otherget/three' endpoint,
            // because it was mapped to v3 with attribute: MapToApiVersion("3")
            options.DocInclusionPredicate((version, desc) =>
            {
                var versions = desc.ControllerAttributes()
                    .OfType<ApiVersionAttribute>()
                    .SelectMany(attr => attr.Versions);

                var maps = desc.ActionAttributes()
                    .OfType<MapToApiVersionAttribute>()
                    .SelectMany(attr => attr.Versions)
                    .ToArray();

                return versions.Any(v => $"v{v.ToString()}" == version) && (maps.Length == 0 || maps.Any(v => $"v{v.ToString()}" == version));
            });

        });

    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint($"/swagger/v2/swagger.json", $"v2");
            c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"v1");
        });
        app.UseMvc();
    }

有两个类可以实现这一点:

public class RemoveVersionFromParameter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var versionParameter = operation.Parameters.Single(p => p.Name == "version");
        operation.Parameters.Remove(versionParameter);
    }
}

public class ReplaceVersionWithExactValueInPath : 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
            );
    }
}

RemoveVersionFromParameter 从 swagger UI 中删除此文本框:

enter image description here

ReplaceVersionWithExactValueInPath 改变了这一点:

enter image description here

对此:

enter image description here

Controller 类现在如下所示:

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

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }


    [HttpGet("otherget/one")]
    [MapToApiVersion("2")]
    public IEnumerable<string> Get2()
    {
        return new string[] { "value1", "value2" };
    }

    /// <summary>
    /// THIS ONE WILL BE EXCLUDED FROM SWAGGER Ui, BECAUSE v3 IS NOT SPECIFIED. 'DocInclusionPredicate' MAKES THE
    /// TRICK 
    /// </summary>
    /// <returns></returns>
    [HttpGet("otherget/three")]
    [MapToApiVersion("3")]
    public IEnumerable<string> Get3()
    {
        return new string[] { "value1", "value2" };
    }
}
<小时/>

代码:https://gist.github.com/Alezis/bab8b559d0d8800c994d065db03ab53e

关于c# - 如何设置 Swashbuckle 与 Microsoft.AspNetCore.Mvc.Versioning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929916/

相关文章:

c# - 接口(interface)和共享实现

c# - 在 C# 中,创建新字节数组时字节的默认值是多少?

c# - DropDownList 设置错误的 SelectedValue

java - 为什么 Swagger Codegen 在从 java 运行时给出配置类未加载错误?

java - 我可以从现有的 Java 代码中获取 Swagger 文档吗?

android - DexArchiveMergerException 仅在发布时出现

c# - 一个列表中多个对象类型的Xml序列化

c# - 抑制 Visual Studio 2015 中的特定分析错误

c# - 手动将 MVC 操作重定向到身份服务器 4 登录页面

c# - ASP.NET 核心 Web API : Required parameter with conditions