如何动态实现api版本控制和swagger文档 [英] How to implement api versioning and swagger document dynamically

查看:25
本文介绍了如何动态实现api版本控制和swagger文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 dotnet core api 中工作.我必须在 api 上实现版本控制.和 swagger 文档应按 api 版本分类.

I am working in dotnet core api. I have to implement versioning on api. and swagger document should be categorized by api version.

推荐答案

在 .NetCore api 中可以通过添加以下来自 nuget 的引用来实现版本控制

In .NetCore api versioning can be implement by adding below reference from nuget

  1. Microsoft.AspNetCore.Mvc.Versioning
  2. Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer

添加引用后,请在项目的启动文件中执行以下操作.在 AddMvc 行之前添加以下行.我将使用 Header-api 版本控制.这意味着客户端将在标题中提及版本.标题名称可自定义.

After adding reference do following in startup file of your project. Add below line before AddMvc line. I will use Header-api versioning. It means client will mention the version in header. Header name is customizable.

 services.AddApiVersioning(this.Configuration);

AddApiVersioning 的定义类似于(在不同的扩展类中):

Definition of AddApiVersioning would be like as (In different extension class):

public static void AddApiVersioning(this IServiceCollection services, IConfiguration configuration)
{
    services.AddApiVersioning(apiVersioningOptions =>
    {
        apiVersioningOptions.ApiVersionReader = new HeaderApiVersionReader(new string[] { "api-version" }); // It means version will be define in header.and header name would be "api-version".
        apiVersioningOptions.AssumeDefaultVersionWhenUnspecified = true;
        var apiVersion = new Version(Convert.ToString(configuration["DefaultApiVersion"]));
        apiVersioningOptions.DefaultApiVersion = new ApiVersion(apiVersion.Major, apiVersion.Minor);
        apiVersioningOptions.ReportApiVersions = true;
        apiVersioningOptions.UseApiBehavior = true; // It means include only api controller not mvc controller.
        apiVersioningOptions.Conventions.Controller<AppController>().HasApiVersion(apiVersioningOptions.DefaultApiVersion);
        apiVersioningOptions.Conventions.Controller<UserController>().HasApiVersion(apiVersioningOptions.DefaultApiVersion);               
        apiVersioningOptions.ApiVersionSelector = new CurrentImplementationApiVersionSelector(apiVersioningOptions);
    });
    services.AddVersionedApiExplorer(); // It will be used to explorer api versioning and add custom text box in swagger to take version number.
}

这里的配置["DefaultApiVersion"] 是 appsetting 中的一个键,值为 1.0在上面的代码中,我们使用约定为每个控制器定义 api 版本.当有一个 api 版本并且您不想用 [ApiVersion] 属性标记每个控制器时,它很有用.

Here configuration["DefaultApiVersion"] is a key in appsetting having value 1.0 As in above code we have used Convention to define api version for each controller. It is useful when there is one api version and you don't want to label each controller with [ApiVersion] attribute.

如果您不想使用约定方法来定义控制器的版本.使用属性标签来定义版本.如下图:

If you don't want to use the Convention menthod to define version of controller. use attribute label to define version. like as below:

[Route("[controller]")]
[ApiController]
[ApiVersion("1.0")]
public class TenantController : ConfigController

完成后转到启动文件并添加以下代码.

Once this done go to StartUp file and add below code.

 app.UseApiVersioning(); //Here app is IApplicationBuilder

这是 api 版本控制的完整解决方案.

That is complete solution for api versioning.

对于 swagger 我们必须添加如下定义的 nuget 包:

  1. Swashbuckle.AspNetCore
  2. Swashbuckle.AspNetCore.SwaggerGen
  3. Swashbuckle.AspNetCore.SwaggerUI添加参考后,请执行以下操作:在 Services.UseApiVersioning() 之后添加以下行

services.AddSwaggerGenerationUI();

services.AddSwaggerGenerationUI();

AddSwaggerGenerationUI 的定义如下:

The definition of AddSwaggerGenerationUI is below in extens :

public static void AddSwaggerGenerationUI(this IServiceCollection services)
{
    var provider = services.BuildServiceProvider()
                     .GetRequiredService<IApiVersionDescriptionProvider>();
    services.AddSwaggerGen(action =>
    {                
        action.OrderActionsBy(orderBy => orderBy.HttpMethod);
        action.UseReferencedDefinitionsForEnums();
        foreach (var item in provider.ApiVersionDescriptions)
        {
            action.SwaggerDoc(item.GroupName, new Swashbuckle.AspNetCore.Swagger.Info
            {
                Title = "Version-" + item.GroupName,
                Version = item.ApiVersion.MajorVersion.ToString() + "." + item.ApiVersion.MinorVersion
            });
        }
    });
}

此代码将在管道中添加招摇.现在我们必须使用招摇.在启动文件中执行以下代码.:

This code will add swagger in pipeline. Now we have to use swagger. do below code in startup file.:

app.UseSwaggerGenerationUI(this.Configuration)

UseSwaggerGenerationUI 的定义如下:

Definition of UseSwaggerGenerationUI would be like as :

public static void UseSwaggerGenerationUI(this IApplicationBuilder applicationBuilder, IApiVersionDescriptionProvider apiVersionDescriptionProvider, IConfiguration configuration)
{
    applicationBuilder.UseSwagger(c =>
    {
        c.RouteTemplate = "/api/help/versions/{documentname}/document.json";

        c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = "/api");
    });

    applicationBuilder.UseSwaggerUI(c =>
    {
        c.RoutePrefix = "api/help";
        c.DocumentTitle = "Api Help";
        foreach (var item in apiVersionDescriptionProvider.ApiVersionDescriptions)
        {
            c.SwaggerEndpoint($"/api/help/versions/{item.GroupName}/document.json", item.GroupName);
        }
    });
}

这篇关于如何动态实现api版本控制和swagger文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆