Search code examples
c#asp.net-coreswaggerminimal-apis

ASP.NET Core Minimal API POST verb raw body swagger empty parameters


I'm using an ASP.NET Core Minimal API, the POST operation reads raw data:

app.MapPost("/Authenticate", async (HttpRequest Request) => {
    string rawContent = string.Empty;
    using (var reader = new StreamReader(Request.Body,
                    encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false))
    {
        rawContent = await reader.ReadToEndAsync();
    }
    // .......
})
.WithName("Authenticate")
.WithOpenApi();

When I run dotnet run command and it opens the browser with the Swagger UI, the endpoint parameters are not available, the endpoint works perfect using Postman + raw post data, but it would be nicer if Swagger UI would allow me to input the raw post body too...

Thank you

Tried with interfaces as input, same result, empty parameters @ Swagger UI ...


Solution

  • You can customize the OpenAPI to include a requestBody schema that accepts raw data. Here is an example you can use as a reference:

    app.MapPost("/Authenticate", async (HttpRequest Request) =>
    {
        string rawContent = string.Empty;
        using (var reader = new StreamReader(Request.Body,
                        encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false))
        {
            rawContent = await reader.ReadToEndAsync();
        }
        
    })
    .WithName("Authenticate")
    .WithOpenApi(openApi =>
    {
        openApi.RequestBody = new OpenApiRequestBody
        {
            Content = new Dictionary<string, OpenApiMediaType>
            {
                {
                    "application/json", new OpenApiMediaType
                    {
                        Schema = new OpenApiSchema
                        {
                            Type = "object" 
                        }
                    }
                }
            },
            Description = "JSON"
        };
    
        return openApi;
    });
    

    enter image description here

    enter image description here