用 Swagger UI 進行測試時,預設是沒有 Header 可以用,當 API 需要用到 Header,要自己手動處理一下,讓 Swagger UI 提供畫面讓開發人員調試
開發環境
- VS 2017 Enterprise 15.9.5
- Swashbuckle 5.6.0
實作步驟
先定義一個 Attribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class HeaderAttribute : Attribute { public string Name { get; set; } public string Type { get; set; } public object[] EnumValues { get; set; } public bool Required { get; set; } public object Default { get; set; } }
依照需求,把掛在 Action 上
public class ValuesController : ApiController { [Header(Name = "Header1", Type = "string", EnumValues = new object[] {1, 2, 3}, Default = "2")] public IEnumerable<string> Get() { return new[] {"value1", "value2"}; } }
實作 IOperationFilter,用來把 Action 上面的 HeaderAttribute,放到Operation.parameters
public class HeaderFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { var headers = apiDescription.ActionDescriptor.GetCustomAttributes<HeaderAttribute>(); if (!headers.Any()) { return; } if (operation.parameters == null) { operation.parameters = new List<Parameter>(); } foreach (var header in headers) { var parameter = new Parameter { name = header.Name, @in = "header", type = header.Type, @enum = header.EnumValues?.ToList(), required = header.Required, @default = header.Default }; operation.parameters.Add(parameter); } } }
在 SwaggerConfig.cs 裡面套用
c.OperationFilter<HeaderFilter>();
運行結果如下
參考來源:
https://github.com/domaindrivendev/Swashbuckle/issues/501
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET