How can I create an example requestBody in OpenAPI using MinimalApi?

102 Views Asked by At

I'm trying to dynamically build a MinimalApi in ASP.Net Core application and I'm struggling with generating a requestBody example.

I tried to solved it like this:

.WithOpenApi(x =>
{
    x.RequestBody = new()
    {
        Content = new Dictionary<string, OpenApiMediaType>()
        {
            { "application/json", new OpenApiMediaType() { Example = new OpenApiString(JsonSerializer.Serialize(new TestClass())) } }
        }
    };
}

I'm getting an error Could not render Dt, see the console. when I open a method in Swagger-UI.

In the console, I have a message TypeError: Cannot read properties of undefined (reading 'toJS').

What is wrong with my approach and how can I set an example of requestBody in OpenAPI?

1

There are 1 best solutions below

0
On BEST ANSWER

I've figured that out. I was missing a Scheme parameter in my OpenApiMediaType. The complete solution looks like this:

.WithOpenApi(x =>
{
    var scheme = new OpenApiSchema()
    {
        Type = typeof(TestClass).ToString(),
        Example = new OpenApiString(JsonSerializer.Serialize(new TestClass()))
    };
    x.RequestBody = new()
    {
        Content = new Dictionary<string, OpenApiMediaType>()
        {
            ["application/json"] = new()
            {
                 Schema = scheme
            }
        }
    };
}