作者:Sunshine丶米粉_499 | 来源:互联网 | 2022-12-10 14:11
当将输入数据作为a发布FormData
到ASP.NET Core MVC控制器时,默认情况下将空字符串值强制为这些null
值。
但是,当将输入数据作为JSON发送到控制器时,空字符串值保持原样。验证string
属性时,这会导致不同的行为。例如,description
field未绑定到null
,而是绑定到服务器上的空字符串:
{
value: 1,
description: ""
}
从而使以下模型无效,即使Description
不是必需的:
public class Item
{
public int Value { get; set; }
[StringLength(50, MinimumLength = 3)]
public string Description { get; set; }
}
这与通过表单提交相同数据时的行为相反。
有没有一种方法可以使JSON的模型绑定行为与表单数据的模型绑定行为相同(默认情况下,空字符串强制转换为null)?
1> Nenad..:
在阅读了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; }
}