3

将输入数据作为 a 发布FormData到 ASP.NET Core MVC 控制器时,默认情况下,空字符串值被强制转换为null值。

但是,当将输入数据作为 JSON 发送到控制器时,空字符串值将保持原样。string这会在验证属性时导致不同的行为。例如,description字段未绑定到null,而是绑定到服务器上的空字符串:

{
    value: 1,
    description: ""
}

这反过来又使以下模型无效,即使Description不是必需的:

public class Item
{
    public int Value { get; set; }

    [StringLength(50, MinimumLength = 3)]
    public string Description { get; set; }
}

这与通过表单提交相同数据时的行为相反。

有没有办法让 JSON 的模型绑定的行为与表单数据的模型绑定相同(空字符串默认强制为 null)?

4

1 回答 1

7

在浏览了ASP.NET Core MVC (v2.1)的源代码和Newtonsoft.Json (v11.0.2)的源代码之后,我想出了以下解决方案。

首先,创建自定义JsonConverter

public class EmptyStringToNullJsonConverter : JsonConverter
{
    public override bool CanRead => true;
    public override bool CanWrite => false;

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string value = (string)reader.Value;
        return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
    }
}

然后,全局注册自定义转换器:

services
    .AddMvc(.....)
    .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new EmptyStringToNullJsonConverter()))

或者,通过JsonConverterAttribute. 例如:

public class Item
{
    public int Value { get; set; }

    [StringLength(50, MinimumLength = 3)]
    [JsonConverter(typeof(EmptyStringToNullJsonConverter))]
    public string Description { get; set; }
}
于 2018-07-17T08:29:07.697 回答