.NetFramework框架
1. 安装Swashbuckle v5.6.0 Nuget包(目前最新版)
2. 解决方案>属性>生成
3. 添加配置
引入Swashbuckle包,App_Start文件夹会自动添加 SwaggerConfig.cs
类,内部方式默认被注释掉了,取消 c.IncludeXmlComments(GetXmlCommentsPath());
该句的注释,并在下方添加方法:
private static string GetXmlCommentsPath()
{
return string.Format(@"{0}\bin\TransactionSearch.xml", AppDomain.CurrentDomain.BaseDirectory);
}
4. 控制器内编写API接口
5. 浏览器执行
输入地址: http://xxxx/swagger
.NetCore框架
1. 引入 Swashbuckle 最新版本
2. 编写文档过滤器
继承 IDocumentFilter
类
public class TagDescriptionsDocumentFilter : IDocumentFilter
{
/// <summary>
/// Apply
/// </summary>
/// <param name="swaggerDoc"></param>
/// <param name="context"></param>
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Tags = new[] {
new Tag{ Name = "PersonTransaction", Description = "个人交易" },
new Tag{ Name = "GroupTransaction", Description = "机构交易" }
};
}
}
3. Startup.cs类中注册
public class Startup
{
private readonly IHostingEnvironment _hostingEnv;
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
_hostingEnv = env;
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().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Title = "xxxx接口",
Version = "v1",
Description = ""
});
// 注释
c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml");
// Tags描述
c.DocumentFilter<TagDescriptionsDocumentFilter>();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/api/Home/Error");
}
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Host = httpReq.Host.Value);
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "xxxx接口");
});
app.UseMvc();
}
}
4. 控制器下编写API接口
core版本的operationId属性设置:[SwaggerOperation(OperationId = "SelectPersonTransaction")]
5. 浏览器执行
执行地址: https://xxxx/swagger