问题描述
我们有以下请求模型:
public class SequenceRequest<TPayload>: SequenceRequest
{
public TPayload Payload { get; set; }
}
Payload 属性是根据 TPayload 的类型有条件地要求的。
有什么方法可以基于此设置 OpenApiParameter 的 required 属性,例如使用 IOperationFilter?
我可以在 OperationFilterContext 中看到很多描述请求的信息,但我不确定我需要覆盖什么。
有人可以举个例子吗?
解决方法
最后,我使用架构过滤器为我的案例找到了解决方案。
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);
}
}
}