Ali_Nass
Ali_Nass

Reputation: 928

Swagger UI using C# webApi is changing my header parameter to query parameter?

So I decided to use this method since it's the simplest to add custom headers for my api calls, example:

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

The expected outcome from this is a field in Swagger where I can input the deviceGuid and Swagger should consider it as a header.

Issue at hand is that Swagger is considering it a query and not a header:

image

Any clue how I can solve this?

Upvotes: 0

Views: 1075

Answers (1)

VisualBean
VisualBean

Reputation: 5008

I dont think SwashBuckle (im guessing this is the swagger implementation you're using), knows about FromHeader.
What you could do, is this;
Make an OperationFilter that changes the ParameterType to Header - something like the following; - note I found this in 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";
        }
    }
}

Upvotes: 1

Related Questions