.NetCore3.0使用Swagger
1.新建一个空白解决方案
2.添加新建项目 ASP.NET Core Web应用程序 - API
3.为项目引用NuGet包
1.Swashbuckle.AspNetCore (勾选包括预发行版,.netcore对应Swashbuckle.AspNetCore 5.0.0-rc4;4.01及以下存在兼容问题;其他版本暂未试用;)
2.Microsoft.OpenApi
3.Microsoft.AspNetCore.Mvc.Versioning
4.Autofac.Extensions.DependencyInjection
4.启用XML注释
5.Startup中启用Swagger
1)ConfigureServices方法中添加如下配置
//swagger
services.AddSwaggerGen(option =>
{
option.SwaggerDoc("Test", new OpenApiInfo
{
Version = "v1",
Title = "测试Api",
Description = "测试Api",
});
option.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API V1" });
option.DocInclusionPredicate((docName, apiDesc) =>
{
var versions = apiDesc.CustomAttributes()
.OfType<ApiVersionAttribute>()
.SelectMany(attr => attr.Versions);
return versions.Any(v => $"v{v.ToString()}" == docName);
});
foreach (var path in GetSwaggerXmls())
{
option.IncludeXmlComments(path, true);
}
});
//跨域
services.AddCors(options =>
{
options.AddPolicy(“AnyOrigin”, builder =>
{
builder.AllowAnyOrigin() //允许任何来源的主机访问
.AllowAnyMethod()
.AllowAnyHeader();
//.AllowCredentials();//指定处理cookie
});
});
2) Configure
//设置全局跨域
app.UseCors(“AnyOrigin”);
app.UseHttpsRedirection();
app.UseSwagger();
//Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint
app.UseSwaggerUI(option =>
{
//option.SwaggerEndpoint("/swagger/v2/swagger.json", "V2 Docs");
option.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
option.RoutePrefix = string.Empty;
option.DocumentTitle = "测试Api";
});
3)
/// <summary>
/// 获取项目注释
/// </summary>
/// <returns></returns>
public static List<string> GetSwaggerXmls()
{
//获取项目.*.xml注释
var xmlPaths = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "DeomPro.*.xml").ToList();
return xmlPaths;
}
6.使用版本号,以及跨域
7.完成,启动项目看下效果