[英]How to document conditionally required property with Swashbuckle
We have the following request model:我们有以下请求 model:
public class SequenceRequest<TPayload>: SequenceRequest
{
public TPayload Payload { get; set; }
}
The Payload property is conditionally required based on the type of the TPayload.根据 TPayload 的类型,有条件地需要Payload属性。
Is there a way how can I set the Required property of the OpenApiParameter based on that, eg using the IOperationFilter?有没有一种方法可以基于此设置 OpenApiParameter 的 Required 属性,例如使用 IOperationFilter?
I can see a lot of information in the OperationFilterContext describing the request, but I am not sure what I need to override.我可以在 OperationFilterContext 中看到很多描述请求的信息,但我不确定我需要覆盖什么。
Could anybody provide an example, please?请问有人可以举个例子吗?
Finally, I got a solution for my case using a schema filter.最后,我使用模式过滤器为我的案例找到了解决方案。
public class PayloadRequiredSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
// from the model definition we know, the type is generic
// and derived from a non-generic SequenceRequest
if (context.Type.IsGenericType && context.Type.IsSubclassOf(typeof(SequenceRequest)))
{
// from the model we know it has one generic argument
var argumentType = context.Type.GenericTypeArguments.First();
// in our case the Payload is not required when it is of the SequencePayload type
if (argumentType.Equals(typeof(SequencePayload)))
{
return;
}
// the Payload is required
// we know the property name
// however, the list of properties is serialized => the key may change based on the serializer options
var propertyName = schema.Properties.Single(p => argumentType.Name.Equals(p.Value.Reference?.Id)).Key;
// mark the property as required
schema.Required.Add(propertyName);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.