.Net Core微服务入门——Swagger接入
一、API接入Swagger
1、引入包:Swashbuckle.AspNetCore
2、修改Startup,在ConfigureServices 中添加 Swagger
public void ConfigureServices(IServiceCollection services)
{
// 添加Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddControllers();
}
3、修改Startup,在Configure方法里面添加Swagger有关的中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// 添加Swagger有关中间件
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1");
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//注册 Consul
this.Configuration.ConsulRegist();
}
4、启动调试,查看结果
https://localhost:49167/swagger
Swagger 成功接入,但是我们发现,只显示了接口,却没有显示相关描述信息。
不着急,我们继续!
二、API Swagger添加描述
1、引入包:Microsoft.Extensions.PlatformAbstractions
2、修改Startup,在ConfigureServices中注入xml相关描述
public void ConfigureServices(IServiceCollection services)
{
// 添加Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// 获取xml文件名
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
// 获取xml文件路径
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// 添加控制器层注释,true表示显示控制器注释
c.IncludeXmlComments(xmlPath, true);
});
services.AddControllers();
//Development、Staging、Production
//AppSetting.SetAppSetting(Configuration.GetSection("ConnectionStrings"));
//设置配置
AppConfiguration.SetConfiguration(Configuration);
//注入数据库
var connStr = Configuration.GetConnectionString("SQLServerConnection");
services.AddDbContext<SqlContext>(builder => builder.UseSqlServer(connStr));
//注入Mysql数据库
var connMysqlStr = Configuration.GetConnectionString("MySQLConnection");
services.AddDbContextPool<MySqlContext>(builder => builder.UseMySql(connMysqlStr, new MySqlServerVersion(new Version(5, 7, 21))));
//services.AddDbContextPool<MySqlContext>(builder => builder.UseMySql(connMysqlStr, new MySqlServerVersion(new Version(8, 0, 11))));
}
3、项目右键,选择属性,勾选“XML文档文件”,如下图所示:
4、选中项目 xxxxx.xml,修改成 如果较新则复制
为什么要这样设置呢,如果不设置的话,发布时候会出问题,找不到 xml文件
4、启动调试,查看结果
https://localhost:49167/swagger
API已经接入了swagger,但是我们是不直接访问api,而是访问网关,那网关怎么接入Swagger呢
三、Ocelot添加Swagger
1、引入包:Swashbuckle.AspNetCore
2、修改Startup,在ConfigureServices 中添加 Swagger
public void ConfigureServices(IServiceCollection services)
{
string consulport = Configuration["consulport"];
if (!string.IsNullOrWhiteSpace(consulport))
{
Configuration["GlobalConfiguration:ServiceDiscoveryProvider:Port"] = consulport;
}
services.AddMvc();
//注入Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo { Title = "Gateway API", Version = "v1", Description = "# gateway api..." });
});
//添加ocelot服务
//services.AddOcelot();
//添加ocelot服务
services.AddOcelot()
//添加consul支持
.AddConsul()
//添加缓存
.AddCacheManager(x =>
{
x.WithDictionaryHandle();
})
//添加Polly
.AddPolly();
}
3、修改Startup,在Configure方法里面添加Swagger有关的中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
//这里要与 UpstreamPathTemplate 相同,支持配置多个
c.SwaggerEndpoint("/myapi/swagger/v1/swagger.json", "MyAPI V1");
});
//设置Ocelot中间件
app.UseOcelot().Wait();
}
4、修改ocelot.json,增加Swagger配置
"Routes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/api/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "MyApi",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"FileCacheOptions": {
"TtlSeconds": 5,
"Region": "regionname"
},
"RateLimitOptions": {
"ClientWhitelist": [ "SuperClient" ], //白名单
"EnableRateLimiting": true, //是否开启限流
"Period": "5s",
"PeriodTimespan": 2,
"Limit": 5
},
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3, //发生错误的次数
"DurationOfBreak": 10000, //熔断时间 毫秒
"TimeoutValue": 5000 //超时时间 毫秒
}
},
{
//引入swagger
"DownstreamPathTemplate": "/swagger/v1/swagger.json",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/myapi/swagger/v1/swagger.json",
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "MyApi",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
]
5、调试启动
https://localhost:49171/swagger/index.html
完成!