使用JSON转换器时如何使用FluentValidation验证输入数据

时间:2019-05-25 22:01:48

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

试图使用FluentValidation进行输入验证,但是由于由于输入数据不正确而首先出现jsonconverter错误的事实,如何将FluentValidation置于json转换器之前?

    public class LoginDto
    {
        public PhoneNumber PhoneNumber { get; set; }
    }

    [JsonConverter(typeof(EmailAddressConverter))]
    public class EmailAddress : ValueObject<string>
    {
        private static readonly EmailAddressAttribute Attr = new EmailAddressAttribute();

        public EmailAddress(string email) : base(email)
        {
            if (!Attr.IsValid(email))
            {
                throw new ArgumentException("Email is not valid", nameof(email));
            }
        }

        public static bool TryParse(string value, out EmailAddress email)
        {
            if (Attr.IsValid(value))
            {
                email = new EmailAddress(value);
                return true;
            }

            email = null;
            return false;
        }
    }

    public class EmailAddressConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            EmailAddress.TryParse(reader.Value?.ToString(), out var email);
            return email;
        }
    }

0 个答案:

没有答案