随笔 - 66  文章 - 0 评论 - 610 trackbacks - 3

services.ConfigureSwaggerGen(options => {
	options.SingleApiVersion(new Info {
		Version = "v1",
		Title = "xxx API",
		Description = "xxx 项目webapi接口说明",
		TermsOfService = "None",
		Contact = new Contact { Name = "xxx", Email = "", Url = "http://xxx.com" },
		License = new License { Name = "xxx", Url = "http://xxx.com" }
	});
	options.IncludeXmlComments(AppContext.BaseDirectory + @"/Admin.xml"); // 这个需要开启项目生成 xml 选项
	options.DocumentFilter<HiddenApiFilter>();
	// 在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成
});
HiddenApiFilter.cs 代码实现部分

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public partial class HiddenApiAttribute : Attribute { }
public class HiddenApiFilter : IDocumentFilter {
	public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) {
		foreach (ApiDescription apiDescription in context.ApiDescriptionsGroups.Items.SelectMany(e => e.Items)) {
			if (apiDescription.GetControllerAttributes().OfType<HiddenApiAttribute>().Count() == 0 
				&& apiDescription.GetActionAttributes().OfType<HiddenApiAttribute>().Count() == 0) continue;

			var key = "/" + apiDescription.RelativePath.TrimEnd('/');
			if (!key.Contains("/test/") && swaggerDoc.Paths.ContainsKey(key))
				swaggerDoc.Paths.Remove(key);
		}
	}
}

 

posted on 2016-11-23 11:05 nicye 阅读(...) 评论(...) 编辑 收藏