net8 WebAP Swagger

WebAPI 使用控制器 和不使用控制器【最小API】



WebAPI 测试用例

Swagger 》》获取注释说明


csharp 复制代码
 #region 配置注释
 string? basePath=Path.GetDirectoryName(typeof(Program).Assembly.Location)??"";
 string xmlPath = Path.Combine(basePath,"WebAPI001.xml");
 options.IncludeXmlComments(xmlPath);
 #endregion

Swagger 版本控制


csharp 复制代码
 builder.Services.AddSwaggerGen(options=>
 {
     #region 配置注释
     string? basePath=Path.GetDirectoryName(typeof(Program).Assembly.Location)??"";
     string xmlPath = Path.Combine(basePath,"WebAPI001.xml");
     options.IncludeXmlComments(xmlPath);
     #endregion
     #region 版本控制
     foreach (var item in typeof(VersionInfo).GetEnumNames())
     {
         options.SwaggerDoc(item, new Microsoft.OpenApi.Models.OpenApiInfo()
         {

             Title = $"{item}:这xxxxWebAPI",
             Version=item,
             Description=$"xxx {item} 版本"
         });

     }
     #endregion
 });
csharp 复制代码
 if (app.Environment.IsDevelopment())
 {
     app.UseSwagger();
     app.UseSwaggerUI(c => {
         foreach (var item in typeof(VersionInfo).GetEnumNames())
         {
             c.SwaggerEndpoint($"/swagger/{item}/swagger.json", $"{item}");
         }
     });
 }

》》 [ApiExplorerSettings(GroupName = nameof(VersionInfo.V3))]

》》定义枚举 版本控制

Swagger Token 这个为了方便 通过Swagger 测量api
csharp 复制代码
 builder.Services.AddSwaggerGen(options =>
 {
     #region 配置注释
     string? basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? "";
     string xmlPath = Path.Combine(basePath, "WebAPI001.xml");
     options.IncludeXmlComments(xmlPath);
     #endregion
     #region 版本控制
     foreach (var item in typeof(VersionInfo).GetEnumNames())
     {
         options.SwaggerDoc(item, new OpenApiInfo()
         {

             Title = $"{item}:这xxxxWebAPI",
             Version = item,
             Description = $"xxx {item} 版本"
         });

     }
     #endregion
     #region Swagger 支持  Token
     options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
     {

         Description = "请录入Token,格式:Bearer xxxx   Bearer 后面必须有个空格",
         Name = "Authorization",
         In = ParameterLocation.Header,
         Type = SecuritySchemeType.ApiKey,
         BearerFormat = "JWT",
         Scheme = "Bearer"
     });
     //添加安全要求
     options.AddSecurityRequirement(new OpenApiSecurityRequirement {
     {
         new OpenApiSecurityScheme{
             Reference =new OpenApiReference{
                 Type = ReferenceType.SecurityScheme,
                 Id ="Bearer"
             }
         },
         new string[]{ }
     }});
     #endregion
 });
Swagger 扩展方法

》》》原来的 program 添加的 Swagger

csharp 复制代码
using Microsoft.OpenApi.Models;
using WebAPI001.Coms;
using static System.Net.WebRequestMethods;

namespace WebAPI001
{

    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(options =>
            {
                #region 配置注释
                string? basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? "";
                string xmlPath = Path.Combine(basePath, "WebAPI001.xml");
                options.IncludeXmlComments(xmlPath);
                #endregion
                #region 版本控制
                foreach (var item in typeof(VersionInfo).GetEnumNames())
                {
                    options.SwaggerDoc(item, new OpenApiInfo()
                    {

                        Title = $"{item}:这xxxxWebAPI",
                        Version = item,
                        Description = $"xxx {item} 版本"
                    });

                }
                #endregion
                #region Swagger 支持  Token
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {

                    Description = "请录入Token,格式:Bearer xxxx   Bearer 后面必须有个空格",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                //添加安全要求
                options.AddSecurityRequirement(new OpenApiSecurityRequirement {
                {
                    new OpenApiSecurityScheme{
                        Reference =new OpenApiReference{
                            Type = ReferenceType.SecurityScheme,
                            Id ="Bearer"
                        }
                    },
                    new string[]{ }
                }});
                #endregion
            });
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    foreach (var item in typeof(VersionInfo).GetEnumNames())
                    {
                        c.SwaggerEndpoint($"/swagger/{item}/swagger.json", $"{item}");
                    }
                });
            }

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

》》》扩展方法之后

csharp 复制代码
using Microsoft.OpenApi.Models;

namespace WebAPI001.Coms
{
    public static class  SwaggerExtension
    {
        /// <summary>
        /// 注册Swagger
        /// </summary>
        /// <param name="services"></param>
        public static void AddSwaggerExt(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                #region 配置注释
                string? basePath = AppContext.BaseDirectory;
                string xmlPath = Path.Combine(basePath, "WebAPI001.xml");
                options.IncludeXmlComments(xmlPath);
                #endregion
                #region 版本控制
                foreach (var item in typeof(VersionInfo).GetEnumNames())
                {
                    options.SwaggerDoc(item, new OpenApiInfo()
                    {

                        Title = $"{item}:这xxxxWebAPI",
                        Version = item,
                        Description = $"xxx {item} 版本"
                    });

                }
                #endregion
                #region Swagger 支持  Token
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {

                    Description = "请录入Token,格式:Bearer xxxx   Bearer 后面必须有个空格",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                //添加安全要求
                options.AddSecurityRequirement(new OpenApiSecurityRequirement {
                {
                    new OpenApiSecurityScheme{
                        Reference =new OpenApiReference{
                            Type = ReferenceType.SecurityScheme,
                            Id ="Bearer"
                        }
                    },
                    new string[]{ }
                }});
                #endregion
            });
        }
        /// <summary>
        /// 添加Swagger中间件
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwaggerExt(this WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                foreach (var item in typeof(VersionInfo).GetEnumNames())
                {
                    c.SwaggerEndpoint($"/swagger/{item}/swagger.json", $"{item}");
                }
            });
        }
    }
}

》》》program 就清爽了很多了

Swagger 带参数
相关推荐
李小白6611 小时前
Spring MVC(上)
java·spring·mvc
王ASC17 小时前
SpringMVC的URL组成,以及URI中对/斜杠的处理,解决IllegalStateException: Ambiguous mapping
java·mvc·springboot·web
撒呼呼17 小时前
# 起步专用 - 哔哩哔哩全模块超还原设计!(内含接口文档、数据库设计)
数据库·spring boot·spring·mvc·springboot
zybishe2 天前
免费送源码:Java+ssm++MVC+HTML+CSS+MySQL springboot 社区医院信息管理系统的设计与实现 计算机毕业设计原创定制
java·hadoop·sql·zookeeper·html·json·mvc
nie66688883 天前
springmvc的拦截器,全局异常处理和文件上传
spring·mvc
王ASC3 天前
Springboot访问到Controller中不存在的接口BUG
spring boot·后端·mvc
de之梦-御风3 天前
【进阶编程】MVVM的物理架构目录
架构·mvc·.net
m0_748247804 天前
WebMvcConfigurer和WebMvcConfigurationSupport(MVC配置)
mvc
喵小狸4 天前
Spring MVC 中,处理异常的 6种方式
python·spring·mvc
小鹿撞出了脑震荡4 天前
「iOS」通过CoreLocation Framework深入了解MVC架构
ios·架构·mvc