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 带参数
相关推荐
人道领域18 小时前
Day | 12 【苍穹外卖 :导出Excel数据表】
java·后端·sql·servlet·mvc·intellij-idea
Lyyaoo.19 小时前
Spring,Spring MVC, Spring Boot
spring boot·spring·mvc
harder32120 小时前
Swift 面向协议编程的 RMP 模式
开发语言·ios·mvc·swift·策略模式
杰克尼2 天前
知识点总结--day07(Spring-MVC框架)
java·spring·mvc
英俊潇洒美少年4 天前
MVC / MVVM 和 Vue3、React18 到底啥关系?
mvc
武超杰5 天前
Spring MVC进阶与SSM整合实战
java·spring·mvc
毕设源码-邱学长6 天前
【开题答辩全过程】以 基于.net mvc剧本杀预约与管理为例,包含答辩的问题和答案
mvc·.net
不想看见4046 天前
QAbstractItemModel 自定义实现--Qt 模型 / 视图(MVC)
开发语言·qt·mvc
cyforkk6 天前
警惕生产环境中的“日志炸弹”:Spring MVC 异常处理最佳实践
spring·mvc·状态模式
洛洛呀。7 天前
DDD架构为何拆分Entity层?从MVC到领域模型的演进之道
架构·mvc·ddd