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

How can I disable model validation for one model type in WebApi?

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

我至少找到了一种方法:

[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();
    }