在使用Swagger需要隐藏不开放的API
可以在SwaggerConfig.cs中加入
/// <summary>
/// 隐藏接口,不生成到swagger文档展示
/// </summary>
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)]
public partial class HiddenApiAttribute : System.Attribute { }
public class HiddenApiFilter : IDocumentFilter
{
/// <summary>
/// 重写Apply方法,移除隐藏接口的生成
/// </summary>
/// <param name="swaggerDoc">swagger文档文件</param>
/// <param name="schemaRegistry"></param>
/// <param name="apiExplorer">api接口集合</param>
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
{
if (Enumerable.OfType<HiddenApiAttribute>(apiDescription.GetControllerAndActionAttributes<HiddenApiAttribute>()).Any())
{
string key = "/" + apiDescription.RelativePath;
if (key.Contains("?"))
{
int idx = key.IndexOf("?", System.StringComparison.Ordinal);
key = key.Substring(0, idx);
}
swaggerDoc.paths.Remove(key);
}
}
}
}
并且在SwaggerConfig.cs 中加入
c.DocumentFilter();
API调实例
/// <summary>
/// 隐藏接口方法生成文档(添加[HiddenApi]特性)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[HiddenApi]
[Route("HideApi")]
[HttpGet]
public HttpResponseMessage HideApi(string value)
{
return Request.CreateResponse(HttpStatusCode.OK, new { errorCode = "0", value = value });
}