一、首先在项目中引入Swashbuckle.AspNetCore;
如果使用ini类型的作为配置文件还需要引入Microsoft.Extensions.Configuration.Ini
二、Program.cs代码:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace MyWebApiDemo
{
public class Program
{
public static void Main(string[] args)
{
//两种方式
CreateHostBuilder(args).Build().Run();
//CreateWebHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear();
config.AddIniFile("Config.ini", optional: false, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
//public static IWebHostBuilder CreateWebHostBuilder(string[] args)
//{
// return WebHost.CreateDefaultBuilder(args)
// .ConfigureAppConfiguration((webhostContext, config) =>
// {
// config.Sources.Clear();
// config.AddIniFile("Config.ini", optional: false, reloadOnChange: true);//配置文件采用Config.ini
// })
// .UseStartup<Startup>();
//}
}
}
三、Startup.cs代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using MyWebApiDemo.Filter;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MyWebApiDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddMvc(options=>
//{
// options.Filters.Add(typeof(CustomResultFilter));
//}).SetCompatibilityVersion(version:CompatibilityVersion.Version_3_0);
services.AddMvc(options =>
{
options.Filters.Add(typeof(FieldActionFilter));
}).SetCompatibilityVersion(version: CompatibilityVersion.Version_3_0);
services.Configure<ApiBehaviorOptions>(options=>
{
options.SuppressModelStateInvalidFilter = true;
});
if (Configuration["system:EnableSwagger"] =="1")
{
services.AddSwaggerGen(c=> {
string json= Configuration["system:ApiGroup"];
List<Item> list = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (Item it in list)
{
//第一个参数,必须与 api 的 GroupName 所使用的值保持一致。
c.SwaggerDoc(it.en, new OpenApiInfo()
{
Version = it.en,//标题的右上角显示
Title = $"{it.cn} API示例",
Description = $"这个是自己开发的 {it.cn} api 示例文档"
});
}
//或者将分组信息放置于cs文件里
//public static Dictionary<string, string> swaggerDic = new Dictionary<string, string>()
//{
// {"Common","公用接口" }
//};
//foreach (KeyValuePair<string, string> kv in Common.swaggerDic)
//{
// //第一个参数,必须与 api 的 GroupName 所使用的值保持一致。
// s.SwaggerDoc(kv.Key, new OpenApiInfo()
// {
// Version = "v1",//标题的右上角显示
// Title = $"{kv.Value} API",
// Description = $"边检产品 {kv.Value} api 文档"
// });
//}
//MyWebApiDemo.xml生成一下项目即可自动生成,无需手动添加
c.IncludeXmlComments("MyWebApiDemo.xml");
});
}
services.AddControllers().AddNewtonsoftJson().AddXmlSerializerFormatters();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
if (Configuration["system:EnableSwagger"] == "1")
{
app.UseSwagger();
app.UseSwaggerUI(c=>
{
string json = Configuration["system:ApiGroup"];
List<Item> list = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (var item in list)
{
c.SwaggerEndpoint($"/swagger/{item.en}/swagger.json", item.cn);
}
});
}
app.UseStaticFiles();
app.UseRouting();
//允许跨域
app.UseCors("any");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name:"name",
pattern: "{controller=WeatherForecast}/{action=Get}/{id?}"
);
});
}
}
public class Item
{
public string en { get; set; }
public string cn { get; set; }
}
}
四、Config.ini
[system]
#组
ApiGroup=[{"en":"group1","cn":"测试组一"},{"en":"group2","cn":"测试组二"},{"en":"WeatherForecast","cn":"气象服务"}]
#是否启用Swagger,1-启用,2-不启用
EnableSwagger=1
五、控制器Controller
using Microsoft.AspNetCore.Mvc;
using System;
using System.Data;
namespace MyWebApiDemo.Controllers
{
[ApiController]
//在控制器上面添加如下代码用于接口分组
[ApiExplorerSettings(GroupName = "group2")]
public class Test2Controller : ControllerBase
{
/// <summary>
/// 测试组2
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("api/[controller]/GetData2")]
public DataTable GetData2()
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("age", typeof(int));
dt.Columns.Add("time", typeof(DateTime));
dt.Rows.Add("张三", 19, "2020-10-19 12:34:56");
dt.Rows.Add("李四", 56, DateTime.Now);
return dt;
}
}
}
六、运行起来效果如下图: