asp.net C#卡在getter和setter与默认值之间

wooyq4lh  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(134)

我在班上有:

public class submitRequest
{
    public int students { get; set; } = 0;

字符串
当我将从前端发送到后端时,发送一个非数字(例如:null或空字符串),它不使用默认值,我得到:

"The JSON value could not be converted to System.Int32. Path: $.students"


但当我只有

public int students { get; } = 0;


很好用。但是我遇到了问题,从前端发送的正确值(1,2,...)被忽略了,学生的值总是0。

ikfrs5lh

ikfrs5lh1#

从前端发送非数字值时不使用默认值的原因是反序列化过程失败并引发异常。
要处理这种情况,可以通过将students属性的类型更改为int?,使其为空:

public class SubmitRequest
{
    public int? Students { get; set; }
}

字符串
通过使属性为空,即使JSON值为空或不是有效整数,反序列化过程也将成功。
如果JSON值为null,则属性将被设置为null。如果JSON值不是有效的整数,则属性也将设置为null。

相关问题