允许将空字符串用于EmailAddressAttribute [英] Allow empty string for EmailAddressAttribute

查看:501
本文介绍了允许将空字符串用于EmailAddressAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的PersonDTO类中有属性:

[EmailAddress]
public string Email { get; set; }

工作正常,除了如果我从客户端发送JSON,我想允许空字符串作为模型的值:

It works fine, except I want to allow empty strings as values for my model, if I send JSON from client side:

{ Email: "" }

我得到了400 bad request响应,并且

{"$id":"1","Message":"The Email field is not a valid e-mail address."}

但是,它可以省略email值:

{ FirstName: "First", LastName: 'Last' }

我也尝试过:

[DataType(DataType.EmailAddress, ErrorMessage = "Email address is not valid")]

但它不起作用.

据我了解,Data Annotations Extensions pack也不允许使用空字符串.

As far as I understood, Data Annotations Extensions pack does not allow empty string either.

因此,我想知道是否有一种方法可以自定义标准EmailAddressAttribute以允许空字符串,因此我不必编写自定义验证属性.

Thus, I wonder if there is a way to customize the standard EmailAddressAttribute to allow empty strings so I do not have to write custom validation attribute.

推荐答案

您有两个选择:

  1. 在电子邮件"字段上将string.Empty转换为null.很多时候,这是完全可以接受的.您可以在全球范围内使用此功能,也可以简单地通过setter将string.Empty转换为null到电子邮件字段.
  2. 写一个自定义的EmailAddress属性,因为EmailAddressAttribute是密封的,您可以包装它并编写自己的转发IsValid方法.

示例:

bool IsValid(object value)
{
    if (value == string.Empty)
    {
        return true;
    }
    else
    {
        return _wrappedAttribute.IsValid(value);
    }
}

扩展选项1(来自 Web API无法将json空字符串值转换为null )

添加此转换器:

public class EmptyToNullConverter : JsonConverter
{
    private JsonSerializer _stringSerializer = new JsonSerializer();

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override object ReadJson(JsonReader reader, Type objectType,
                                    object existingValue, JsonSerializer serializer)
    {
        string value = _stringSerializer.Deserialize<string>(reader);

        if (string.IsNullOrEmpty(value))
        {
            value = null;
        }

        return value;
    }

    public override void WriteJson(JsonWriter writer, object value, 
                                   JsonSerializer serializer)
    {
        _stringSerializer.Serialize(writer, value);
    }
}

并在该属性上使用:

[JsonConverter(typeof(EmptyToNullConverter))]
public string EmailAddress {get; set; }

或在WebApiConfig.cs中全局:

or globally in WebApiConfig.cs:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
    new EmptyToNullConverter());

这篇关于允许将空字符串用于EmailAddressAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆