使用Swagger处理Api的显示与隐藏

一、在SwaggerConfig.cs中配置如下:

c.DocumentFilter();
c.DocumentFilter();

 

二、新建类,分别处理Show与Hide

public class ShowApiAttribute : Attribute { }
public class ShowApiFilter : IDocumentFilter
{
	public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
	{
		foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
		{
			if (!Enumerable.OfType(apiDescription.GetControllerAndActionAttributes()).Any())
			{
				string key = "/" + apiDescription.RelativePath;
				if (key.Contains("?"))
				{
					int idx = key.IndexOf("?", StringComparison.Ordinal);
					key = key.Substring(0, idx);
				}
				swaggerDoc.paths.Remove(key);
			}
		}
	}
}

  

public class HideApiAttribute : Attribute { }
public class HideApiFilter : IDocumentFilter
{
	public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
	{
		foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
		{
			if (Enumerable.OfType(apiDescription.GetControllerAndActionAttributes()).Any())
			{
				string key = "/" + apiDescription.RelativePath;
				if (key.Contains("?"))
				{
					int idx = key.IndexOf("?", StringComparison.Ordinal);
					key = key.Substring(0, idx);
				}
				swaggerDoc.paths.Remove(key);
			}
		}
	}
}

 

三、在使用时,直接在Controller上或Action上加上相应的特性即可,注意,如果上面的代码都放在了项目中,即把显示与隐藏都配置到了Swagger中,则在不加特性时,Swagger的文档中是不显示的

转载于:https://www.cnblogs.com/evasunny/p/10051953.html

你可能感兴趣的:(使用Swagger处理Api的显示与隐藏)