• .NetCore(.NET6)中使用swagger和swagger版本控制


     


    一、.NET6中使用swagger

     swagger支持 API 自动生成同步的在线文档,下面在.NET6中引入

    1.建.NET6应用并建以下控制器

    复制代码
    /// <summary>
        /// 订单接口
        /// </summary>
        [ApiController]
        [Route("[controller]/[action]")]
        public class OrderController : Controller
        {
            /// <summary>
            /// 获取订单
            /// </summary>
            /// <returns></returns>
            [HttpGet]
            public string GetOrder()
            {
                return "ok";
            }
            /// <summary>
            /// 创建订单
            /// </summary>
            /// <param name="request">订单信息</param>
            /// <returns></returns>
            [HttpPost]
            public string CreateOrder([FromBody] OrderRequest request)
            {
                return "ok";
            }
            /// <summary>
            /// 删除订单
            /// </summary>
            /// <returns></returns>
            [HttpDelete]
            public string DeleteOrder()
            {
                return "ok";
            }
            /// <summary>
            /// 更新订单
            /// </summary>
            /// <returns></returns>
            [HttpPut]
            public string UpdateOrder()
            {
                return "ok";
            }
    
        }
    复制代码
    复制代码
      /// <summary>
        /// 订单请求
        /// </summary>
        public class OrderRequest
        {
            /// <summary>
            /// 订单名称
            /// </summary>
            public string orderName { get; set; }
            /// <summary>
            /// 订单编号
            /// </summary>
            public string orderNo { get; set; }
            /// <summary>
            /// 价格
            /// </summary>
            public decimal price { get; set; }
        }
    复制代码

     

     

    2.Nuget包安装swagger需要dll

    Swashbuckle.AspNetCore

    3.Program.cs中加入swagger

    复制代码
    using Microsoft.OpenApi.Models;
    using System.Reflection;
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    builder.Services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "API标题",
            Description = "API描述"
        });
    });
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    复制代码

    这时候访问 http://localhost:xxx/swagger/index.html 已经能访问和显示接口了,但是少了注释

     

     4.生成xml文件,接口文档生成注释需要程序集的xml文件

    打开项目的.csproj文件加上标识让程序生成这个程序集的文档

     

     

     <GenerateDocumentationFile>true</GenerateDocumentationFile>

    5.在Program.cs处加上加载这个xml文件

    完整的 Program.cs文件

    复制代码
    using Microsoft.OpenApi.Models;
    using System.Reflection;
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    builder.Services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "API标题",
            Description = "API描述"
        });
        var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
    });
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    复制代码

    这时再运行就能看到注释了

     

     注意:如果参数的Model在其它类库,那么所引用的类库的.csproj文件也要加上上面的标识,并在Program.cs引入程序集的xml文件才能展示参数的注释。

     

    二、.NET6中使用swagger版本控制

     1.增加文件 ApiVerionInfo.cs记录版本号

    复制代码
      /// <summary>
        /// api版本号
        /// </summary>
        public class ApiVersionInfo
        {
            public static string V1;
            public static string V2;
            public static string V3;
            public static string V4;
            public static string V5;
        }
    复制代码

     

    2.在api控制器上增加版本

     

     

       [ApiExplorerSettings(GroupName =nameof(ApiVersionInfo.V1))]

    3.再建一个控制器,写v2版本的接口

    复制代码
    /// <summary>
        ///  订单接口
        /// </summary>
        [ApiController]
        [Route("[controller]/[action]")]
        [ApiExplorerSettings(GroupName = nameof(ApiVersionInfo.V2))]
        public class OrderV2Controller : Controller
        {
            /// <summary>
            /// 获取订单
            /// </summary>
            /// <returns></returns>
            [HttpGet]
            public string GetOrder()
            {
                return "ok";
            }
            /// <summary>
            /// 创建订单
            /// </summary>
            /// <param name="request">订单信息</param>
            /// <returns></returns>
            [HttpPost]
            public string CreateOrder([FromBody] OrderRequest request)
            {
                return "ok";
            }
        }
    复制代码

    4.Program.cs中swagger的引入

    完整配置:

    复制代码
    using Microsoft.OpenApi.Models;
    using Swagger.Demo;
    using System.Reflection;
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    builder.Services.AddSwaggerGen(options =>
    {
        foreach (FieldInfo fileld in typeof(ApiVersionInfo).GetFields())
        {
            options.SwaggerDoc(fileld.Name, new OpenApiInfo
            {
                Version = fileld.Name,
                Title = "API标题",
                Description = $"API描述,{fileld.Name}版本"
            });
           
        }
        var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
    });
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields())
            {
                c.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}");
            }
        });
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    复制代码

     

    5.配置完成,查看效果

     

     

     

     到这里版本控制就完成了!

  • 相关阅读:
    【付费推广】常见问题合集,搜索推广FAQ 1
    IDEA中使用注解Test
    cad怎么转为黑白pdf
    sql注入(8), 常见注入绕过技巧
    什么是物理信息系统(cps)?
    哈希算法(一)Java实现常用的哈希算法
    2021年9月电子学会图形化四级编程题解析含答案:小猫钓鱼
    解决库存超卖问题
    深度学习知识点:循环神经网络(RNN)、长短期记忆网络(LSTM)、门控循环单元(GRU)
    Java绘图-第19章
  • 原文地址:https://www.cnblogs.com/wei325/p/16047807.html