c# 调试模式下Swaggerf附加接口参数,如:每个接口Header中附加参数appId
1、新增过滤器:
public class GlobalHttpHeaderFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter { name = "appId", @in = "header", description = "应用ID", required = true, type = "string" });
}
}
2、WebAPIConfig 配置Swagger过滤器:
if ( System.Diagnostics.Debugger.IsAttached) //调试模式
{
_config.EnableSwagger(c =>
{
c.SingleApiVersion("v1", $"{name}的API文档");
c.IncludeXmlComments($@"{AppDomain.CurrentDomain.BaseDirectory}\{name}.XML");
c.OperationFilter< GlobalHttpHeaderFilter>();
}).EnableSwaggerUi();
}
3、控制器:
public class DemoAPIController : ApiController
{
Logger log;
/// <summary>
///
/// </summary>
/// <param name="log"></param>
public DemoAPIController(Logger log)
{
this.log = log;
}
/// <summary>
/// 获取数据
/// </summary>
/// <returns>数据</returns>
public string Get()
{
IEnumerable<string> values = null;
if (controller.Request.Headers != null && controller.Request.Headers.TryGetValues(name, out values) && values != null && values.Count() > 0)
{
var appId = values.FirstOrDefault();
}
return "demo";
}
}
4、Swagger: