Im using Swagger in .NET 5
After click on Try it out Swagger displays a "string" in the body. (Please see the below screenshot)
I want it to display "{}" instead.
That's what I tried:
public class EmptyStringRequestBodyFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var schema = operation.RequestBody?.Content?.FirstOrDefault().Value?.Schema;
if (schema != null)
{
foreach (var property in schema.Properties)
{
if (property.Value.Type == "string")
{
property.Value.Example = new OpenApiString("{}");
property.Value.Default = new OpenApiString("{}");
}
}
}
}
}
and on Startup.cs :
services.AddTransient<IOperationFilter, EmptyStringRequestBodyFilter>();
but it didn't help, I still get "string".
As I check how swagger generates by going to link http://localhost:<port>/swagger/v1/swagger.json
I see this
"requestBody": {
"content": {
"application/json-patch+json": {
"schema": { }
},
Seems like it use some default value..
How can I replace to "{}" or just have empty?
Thx.
The following has been working for me:
public class MyClassSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context.Type == typeof(MyClass))
{
schema.Properties.Clear();
schema.Type = "object";
}
}
}
and on Startup.cs:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AAA", Version = "v1" });
c.SchemaFilter<StartSessionSchemaFilter>();
});