ASP.NET Core MVC-将JSON发送到服务器时为空字符串为null

Nen*_*nad 1 json.net asp.net-core-mvc asp.net-core-mvc-2.1

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

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

{
    value: 1,
    description: ""
}
Run Code Online (Sandbox Code Playgroud)

从而使以下模型无效,即使Description不是必需的:

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

    [StringLength(50, MinimumLength = 3)]
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

有没有一种方法可以使JSON的模型绑定行为与表单数据的模型绑定行为相同(默认情况下,空字符串强制转换为null)?

Nen*_*nad 5

在阅读了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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

services
    .AddMvc(.....)
    .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new EmptyStringToNullJsonConverter()))
Run Code Online (Sandbox Code Playgroud)

或者,通过逐个属性地使用它JsonConverterAttribute。例如:

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

    [StringLength(50, MinimumLength = 3)]
    [JsonConverter(typeof(EmptyStringToNullJsonConverter))]
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)