• Asp.net core Swashbuckle Swagger 的常用配置


    背景

      .net core Swashbuckle Swagger 官方文档:https://github.com/domaindrivendev/Swashbuckle.AspNetCore

    我们发现很多小伙伴日常使用 Swashbuckle Swagger 都不看文档的,写下常需用到的配置/写法;

    基本使用

    Package Manager : Install-Package Swashbuckle.AspNetCore
    

    记得用swagger一定要给action打[httpmehtod]标签

    [HttpGet]
    public IEnumerable<Product> SearchProducts([FromQuery]string keywords)
    
    public static IServiceCollection AddSwagger(this IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "test api",
            });
    
            //多个xml文件
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            var dtoXmlPath = Path.Combine(AppContext.BaseDirectory, $"{typeof(BaseIdEntity).Assembly.GetName().Name}.xml");
            c.IncludeXmlComments(xmlPath);
            c.IncludeXmlComments(dtoXmlPath);
        });
    
        return services;
    }
    
    public static IApplicationBuilder UseSwagger(this IApplicationBuilder app)
    {
        //配置二级目录
        var basePath = "/testapi";
        app.UseSwagger(c =>
        {
            c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{basePath}" } });
        });
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint($"{ basePath}/swagger/v1/swagger.json", "FitnessApi V1");
        });
    
        return app;
    }
    

    多版本支持

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API - V1", Version = "v1" });
        c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API - V2", Version = "v2" });
    })
    
    [HttpPost]
    [ApiExplorerSettings(GroupName = "v2")]
    public void Post([FromBody]Product product)
    

    更完善的枚举支持

    Install-Package Unchase.Swashbuckle.AspNetCore.Extensions
    
    services.AddSwaggerGen(options =>
        {
    		//...
    		
            // or configured:
            options.AddEnumsWithValuesFixFilters(services, o =>
            {
                // add schema filter to fix enums (add 'x-enumNames' for NSwag) in schema
                o.ApplySchemaFilter = true;
    
                // add parameter filter to fix enums (add 'x-enumNames' for NSwag) in schema parameters
                o.ApplyParameterFilter = true;
    
                // add document filter to fix enums displaying in swagger document
                o.ApplyDocumentFilter = true;
    
                // add descriptions from DescriptionAttribute or xml-comments to fix enums (add 'x-enumDescriptions' for schema extensions) for applied filters
                o.IncludeDescriptions = true;
    
                // add remarks for descriptions from xml-comments
                o.IncludeXEnumRemarks = true;
    
                // get descriptions from DescriptionAttribute then from xml-comments
                o.DescriptionSource = DescriptionSources.DescriptionAttributesThenXmlComments;
    
                // get descriptions from xml-file comments on the specified path
                // should use "options.IncludeXmlComments(xmlFilePath);" before
                o.IncludeXmlCommentsFrom(xmlFilePath);
                // the same for another xml-files...
            });
        });
    

    枚举文档效果

    image-20210604150951229

    OAuth2.0支持

    Install-Package Swashbuckle.AspNetCore.Filters
    

    手填AccessToken(apikey)方式

     services.AddSwaggerGen(c =>
        {
            //...
            
            c.OperationFilter<SecurityRequirementsOperationFilter>();
            c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Description = "Standard Authorization header using the Bearer scheme. Example: "bearer {token}"",
                In = ParameterLocation.Header,
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey
            });
        });
    

    效果

    image-20210604165307573

    引导跳转OAuth服务器方式

     services.AddSwaggerGen(c =>
        {
            //...
            
            c.OperationFilter<SecurityRequirementsOperationFilter>();
            c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Type = SecuritySchemeType.OAuth2,
                Flows = new OpenApiOAuthFlows()
                {
                    Implicit = new OpenApiOAuthFlow()
                    {
                        AuthorizationUrl = new Uri("https://your.identityserver.io/connect/authorize"),
                        Scopes = new Dictionary<string, string>
                        {
                            { "testapi.rw",  "授权访问测试TestApi" }
                        }
                    }
                }
            });
    
        });
    
    app.UseSwaggerUI(c =>
    {
        //...
        c.OAuthClientId("test_swaager");
    });
    

    效果

    image-20210604165804715

    忽略某个Api

    [HttpGet("{id}")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public Product GetById(int id)
    

    修改传输数据类型

     services.AddSwaggerGen(c =>
     {
    	//long类型转string
     	c.MapType<long>(() => new OpenApiSchema { Type = "string" });
     });
    

    自定义描述(标签)

    Install-Package Swashbuckle.AspNetCore.Annotations
    
    [SwaggerTag("Create, read, update and delete Products")]
    public class ProductsController
    {
        ...
    }
    
  • 相关阅读:
    经典音乐插曲推荐![附地址]
    广播电台常用51首背景音乐——绝对经典
    酒吧..夜店常用歌曲~潮人必备音乐噢~【附下载地址】
    ASP与ASP.NET互通COOKIES的一点经验
    linux进程状态浅析
    常用的酒吧经典乐曲106首
    呼和浩特电视台媒资管理系统的设计与分析
    不再为DataGrid生成的表格的单无格中的内容过长、自动折行、表格撑开等问题而烦恼
    Linux shell脚本全面学习
    ASP.NET文件管理显示信息
  • 原文地址:https://www.cnblogs.com/xiaxiaolu/p/14850372.html
Copyright © 2020-2023  润新知