如何在 WebAPI 中禁用一种模型类型的模型验证

本文关键字:模型 一种 类型 验证 WebAPI | 更新日期: 2023-09-27 18:37:25

我有一个WebApi端点,它接受一个MailMessage对象(来自 System.Net)。我已经定义了自定义 JsonConverters,以便 MailMessage 正确反序列化。但是,我运行它遇到了一个问题,因为DefaultBodyModelValidator遍历对象图并尝试访问其中一个附件中Stream对象的属性,但失败了。如何禁用 MailMessage 类及其下所有内容的遍历?

如何在 WebAPI 中禁用一种模型类型的模型验证

我找到了至少一种方法可以做到这一点:

[JsonConverter(typeof(SuppressModelValidationJsonConverter))]
public sealed class SuppressModelValidation<TValue>
{
    private readonly TValue _value;
    public SuppressModelValidation(TValue value)
    {
        this._value = value;
    }
    // this must be a method, not a property, or otherwise WebApi will validate
    public TValue GetValue()
    {
        return this._value;
    }
}
internal sealed class SuppressModelValidationJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // GetGenericArguments(Type) from http://www.codeducky.org/10-utilities-c-developers-should-know-part-two/
        return objectType.GetGenericArguments(typeof(SuppressModelValidation<>)).Length > 0;
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var valueType = objectType.GetGenericArguments(typeof(SuppressModelValidation<>)).Single();
        var value = serializer.Deserialize(reader, valueType);
        return value != null ? Activator.CreateInstance(objectType, value) : null;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

在控制器中,我有:

    public Task Send([FromBody] SuppressModelValidation<MailMessage> message)
    {
        // do stuff with message.GetValue();
    }