Swagger and swagger version control are used in. NETCORE (. Net6)

Time:2022-5-6

1、 Using swagger in. Net 6

Swagger supports the API to automatically generate synchronized online documents, as shown below Net 6

1. Construction Net6 application and build the following controllers

/// 
    ///Order interface
    /// 
    [ApiController]
    [Route("[controller]/[action]")]
    public class OrderController : Controller
    {
        /// 
        ///Get order
        /// 
        /// 
        [HttpGet]
        public string GetOrder()
        {
            return "ok";
        }
        /// 
        ///Create order
        /// 
        ///Order information
        /// 
        [HttpPost]
        public string CreateOrder([FromBody] OrderRequest request)
        {
            return "ok";
        }
        /// 
        ///Delete order
        /// 
        /// 
        [HttpDelete]
        public string DeleteOrder()
        {
            return "ok";
        }
        /// 
        ///Update order
        /// 
        /// 
        [HttpPut]
        public string UpdateOrder()
        {
            return "ok";
        }

    }
/// 
    ///Order request
    /// 
    public class OrderRequest
    {
        /// 
        ///Order name
        /// 
        public string orderName { get; set; }
        /// 
        ///Order number
        /// 
        public string orderNo { get; set; }
        /// 
        ///Price
        /// 
        public decimal price { get; set; }
    }

 

 

2. Nuget package requires DLL to install swagger

Swashbuckle.AspNetCore

3.Program. Adding swagger to 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 title",
        Description = "API description"
    });
});

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();

Visit at this time http://localhost:xxx/swagger/index.html The interface can be accessed and displayed, but the comments are missing

 

4. Generate the XML file, and generate the XML file of the assembly required for the annotation of the interface document

Open the of the project The csproj file is identified so that the program generates the documentation of the assembly

 

 

true

5. In program Add this XML file at CS

Complete program CS file

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 title",
        Description = "API description"
    });
    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();

Then run again and you can see the comments

 

Note: if the model of the parameter is in other class libraries, the of the referenced class library Csproj files should also be marked with the above logo and displayed in program CS the XML file of the assembly is imported to show the comments of the parameters.

 

2、 Using swagger version control in. Net 6

1. Add the file apiverioninfo CS record version number

/// 
    ///API version number
    /// 
    public class ApiVersionInfo
    {
        public static string V1;
        public static string V2;
        public static string V3;
        public static string V4;
        public static string V5;
    }

 

2. Add version on API controller

 

 

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

3. Build another controller and write the V2 version interface

/// 
    ///Order interface
    /// 
    [ApiController]
    [Route("[controller]/[action]")]
    [ApiExplorerSettings(GroupName = nameof(ApiVersionInfo.V2))]
    public class OrderV2Controller : Controller
    {
        /// 
        ///Get order
        /// 
        /// 
        [HttpGet]
        public string GetOrder()
        {
            return "ok";
        }
        /// 
        ///Create order
        /// 
        ///Order information
        /// 
        [HttpPost]
        public string CreateOrder([FromBody] OrderRequest request)
        {
            return "ok";
        }
    }

4.Program. Introduction of swagger in CS

Full configuration:

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 title",
            Description = $"API description, {fileld. Name} version"
        });
       
    }
    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. After configuration, check the effect

 

 

 

Here, version control is complete!