ASP.NET Core MVC-将JSON发送到服务器时为空字符串为null [英] ASP.NET Core MVC - empty string to null when sending JSON to server

查看:763
本文介绍了ASP.NET Core MVC-将JSON发送到服务器时为空字符串为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When posting input data as a FormData to the ASP.NET Core MVC controller, by default empty string values are coerced to null values.

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

However, when sending input data as JSON to the controller, empty string values remain as they are. This leads to different behavior when validating string properties. For example, description field is not bound to null, but to empty string on the server:

{
    value: 1,
    description: ""
}

这又使以下模型无效,即使不需要Description:

This in turn makes following model invalid, even though Description is not required:

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

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

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

This is contrary to the behavior when same data is submitted via form.

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

Is there a way to make model binding of JSON behave in the same way as model binding of form data (empty string coerce to null by default)?

推荐答案

浏览了ASP.NET Core MVC(v2.1)和 Newtonsoft.Json(v11.0.2),我想出了以下解决方案.

After going through source code of ASP.NET Core MVC (v2.1) and source code of Newtonsoft.Json (v11.0.2), I came up with following solution.

首先,创建自定义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.");
    }
}

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

Then, register custom converter globally:

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

或者,通过JsonConverterAttribute在每个属性的基础上使用它.例如:

Or, use it on per-property bases via JsonConverterAttribute. For example:

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

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

这篇关于ASP.NET Core MVC-将JSON发送到服务器时为空字符串为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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