1

根据 docs, IgnoreDataMember 属性只应在序列化期间考虑。

然而,据我所见,MVC 模型绑定也在 * de * json 序列化期间使用它。

考虑以下类:

public class Tax
{
    public Tax() { }

    public int ID { get; set; }

    [Required]
    [Range(1, int.MaxValue)]
    [IgnoreDataMember]
    public int PropertyId { get; set; }
}

如果将以下 json 字符串 POST/PUT 到操作方法:

{"Position":0,"Description":"State sales tax","Rate":5,"RateIsPercent":true,"PropertyId":1912}

我收到以下验证错误:

{
  "Message": "The request is invalid.",
  "ModelState": {
    "newTax.PropertyId": [
      "The field PropertyId must be between 1 and 2147483647."
    ]
  }
}

[Range(1, int.MaxValue)][Required]属性均无效。

如果我删除该[IgnoreDataMember]属性,一切正常。

是否可以使用不同的属性来告诉 MVC 绑定在反序列化期间不要忽略该属性?

这仅在发布 json 字符串时发生。如果我发布名称/值字符串,一切正常。

4

1 回答 1

2

The answer has to do with the behavior of Json.net. That's what the model binding is using and it's checking IgnoreDataMember for both serialization and deserialization making it useless for me (since I want to only use it for serialization).

The JsonIgnore attribute works exactly the same way.

Given that, I pulled all the ignore attributes off my properties and switched to using json.net's conditional serialization methods.

So basically add this for the above PropertyId field:

public bool ShouldSerializePropertyId() { return false; }

That allows deserialization to come in but blocks serialization from going out.

于 2013-04-18T18:07:51.133 回答