iT邦幫忙

0

[Swagger] 在 Swagger UI 新增自訂 Header

  • 分享至 

  • xImage
  •  

先定義一個 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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言