swagger配置

1.引入Swagger包。

nuget引入Swashbuckle.AspNetCore

 

2、配置Swagger中间件

在Startup类ConfigureServices方法中添加Swagger服务并配置文档信息

 

services.AddSwaggerGen(c =>
            {
                // 使用反射获取xml文件。并构造出文件的路径 //需要在项目-属性-生成里面勾上XML文档文件
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                // 启用xml注释. 该方法第二个参数启用控制器的注释,默认为false.
                c.IncludeXmlComments(xmlPath, true);
                //Bearer 的scheme定义
                var securityScheme = new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    //参数添加在头部
                    In = ParameterLocation.Header,
                    //使用Authorize头部
                    Type = SecuritySchemeType.Http,
                    //内容为以 bearer开头
                    Scheme = "bearer",
                    BearerFormat = "JWT"
                };
                //把所有方法配置为增加bearer头部信息
                var securityRequirement = new OpenApiSecurityRequirement
                    {
                        {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                    {
                                        Type = ReferenceType.SecurityScheme,
                                        Id = "Bearer"
                                    }
                                },
                                new string[] { }
                        }
                    };
                //注册到swagger中
                c.AddSecurityDefinition("Bearer", securityScheme);
                c.AddSecurityRequirement(securityRequirement);
            });

接口信息标记

 展示效果

 

最后Configure中增加

    app.UseSwagger();

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

 

configureServices中

c.SwaggerDoc("V1", new OpenApiInfo { Title = "计划任务", Version = "V1" });
c.SwaggerDoc("V2", new OpenApiInfo { Title = "My API2", Version = "V2" });

Configure中

options.SwaggerEndpoint($"/swagger/V1/swagger.json", "V1");
options.SwaggerEndpoint($"/swagger/V2/swagger.json", "V2");

控制器中

 结果

 根据控制上分组标记 动态呈现方式 -----未完待续

posted @ 2023-07-04 16:46  陌陌逸帆  阅读(211)  评论(0编辑  收藏  举报