使用C#webApi的Swagger UI将我的标头参数更改为查询参数?

时间:2018-08-28 09:07:59

标签: c# asp.net-web-api http-headers swagger

所以我决定使用此方法,因为这是为我的api调用添加自定义标头的最简单方法,例如:

[HttpPost]
[Route("something")]
public async Task<somethingObject> DoSomething([Microsoft.AspNetCore.Mvc.FromHeader(Name = "deviceGuid")] string deviceGuid)
{
    var somethingObject= await doSomethingWithDevice(deviceGuid)
    return somethingObject;
}

预期结果是Swagger中的一个字段,我可以在其中输入deviceGuid,而Swagger应该将其视为标头。

眼前的问题是Swagger正在将其视为查询而不是标头:

image

有什么线索可以解决吗?

1 个答案:

答案 0 :(得分:1)

我不认为SwashBuckle(我想这是您正在使用的敏捷实现)知道FromFromer。
你能做的就是这个
创建一个将ParameterType更改为Header的OperationFilter-类似于以下内容; -请注意,我是在this gist中找到的。

public class FromHeaderAttributeOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        foreach (var httpParameterDescriptor in apiDescription.ActionDescriptor.GetParameters().Where(e => e.GetCustomAttributes<FromHeaderAttribute>().Any()))
        {
            var parameter = operation.parameters.Single(p => p.name == httpParameterDescriptor.ParameterName);
            parameter.name = httpParameterDescriptor.GetCustomAttributes<FromHeaderAttribute>().Single().HeaderName;
            parameter.@in = "header";
        }
    }
}