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

包子wxl發表於2022-03-24

一、.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.配置完成,檢視效果

 

 

 

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

相關文章