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

时间:2015-01-12 23:06:32

标签: c# validation asp.net-web-api

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

1 个答案:

答案 0 :(得分:1)

我发现至少有一种方法可以做到这一点:

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