.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.配置完成,查看效果

 

 

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM