Search code examples
c#swaggerswashbuckleminimal-apis

Minimal API - Define Swagger Header Parameters


I'm creating a minimal API using Swagger and C#. I can't really understand how i define the header parameters. Something like [SwaggerHeaderParameter("apikey", "description...")] or similar. I have searched everywhere but can't seem to find a (what seems to me) a relatively simple solution for this. Can someone help me?

Example code:

using Swashbuckle.AspNetCore;

app.MapPut("/myapi",
[SwaggerResponse(200, "Success")]
[SwaggerResponse(400, "Bad request")]
    async Task<IResult> (HttpRequest request, ILogger<Program> log, CancellationToken ct) =>
    {
         var result = await request.ReadFromJsonAsync<MyClass[]>(request.HttpContext.RequestAborted);
         // [Required] Unique api key for this specific combination of supplierID and Stocknumber.
         var apikey = request.Headers["apikey"].ToString();
                    
            return Results.Ok(successList);
                
     })
     .Accepts<MyClass[]>(false, "application/json")
     .Produces<string[]>(StatusCodes.Status200OK, "text/plain")
     .Produces<Error>(StatusCodes.Status400BadRequest)

*Edit with the help of @Guru Stron

My call is now:

app.MapPut("/myapi",
[SwaggerResponse(200, "Success")]
[SwaggerResponse(400, "Bad request")]
    async Task<IResult> (HttpRequest request, [FromHeader] string apikey, ILogger<Program> log, CancellationToken ct) =>
    {
       ...
    })
...

Solution

  • You can try binding parameter from header:

    app.MapGet("/testHeader", ([FromHeader] string apikey) => "Hello World!");
    

    enter image description here