In the previous post, I show how to reliably determine if a property is nullable for a given Type. I needed to do this because the JSON schema produced by Swagger has incorrect nullability.
This is the JSON schema produced by Swagger for the Movie class in the previous post. The title
should not be nullable.
I find that you can add a Schema Filter which allows you to modify the schemas after they are generated. Using the solution from the previous post to determine if a property is nullable and schema filter, I can modify the nullable
field to match the Movie model.
public class NullablePropertySchemaFilter : ISchemaFilter
{
private NullabilityInfoContext _nullabilityContext = new NullabilityInfoContext();
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema?.Properties == null)
{
return;
}
foreach (var property in context.Type.GetProperties())
{
var schemaProp = schema.Properties
.SingleOrDefault(x => x.Key.ToLower() == property.Name.ToLower());
if (schemaProp.Key == null)
continue;
var nullabilityInfo = _nullabilityContext.Create(property);
schemaProp.Value.Nullable = nullabilityInfo.WriteState == NullabilityState.Nullable;
}
}
}
Then in Startup.cs where you add Swagger, add the schema filter as followed
services.AddSwaggerGen(options =>
{
options.SchemaFilter<NullablePropertySchemaFilter>();
});
The result JSON schema now looks correct