我正在使用 Core 3 构建一个 Web API 微服务。我有一个定义如下的类:
public class UserSourceList
{
[JsonIgnore]
public string UserId { get; set; }
[JsonIgnore]
public string ListId { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ListTypes ListType { get; set; }
public List<string> Ids { get; set; }
public DateTimeOffset CreationTime { get; set; }
}
当框架尝试绑定(bind) HTTP PUT
提供的数据时,它不会填充 UserId
和 ListId
字段。因此,模型绑定(bind)在验证期间失败并返回 HTTP 400
,指出需要 UserId
和 ListId
。
Controller 的action方法定义如下:
[HttpPut("{userId:userid}/{listId:listid}", Name = "ReplaceUserList")]
public ActionResult Replace(string userId, string listId, UserSourceList model)
{
return Ok(_listManager.ReplaceUserList(model.UserId, model.ListId, model));
}
对 API 的典型调用类似于以下内容:
PUT /api/v1/listmgmt/abc123def456/c788f2f7b7984424910726d4a290be26
PUT
主体
{
"name": "Test",
"listType": "Eans",
"ids": ["97814571867716", "9781430257615", "9780982550670"],
"userId":"abc123def456",
"listId":"c788f2f7b7984424910726d4a290be26"
}
如果我从模型的 UserId
和 ListId
属性中删除 JsonIgnore
属性,一切都会按预期绑定(bind)。
模型绑定(bind)将忽略带有 JsonIgnore
标记的字段,这是预期的行为吗?
我知道我可以通过更改验证代码的工作方式来解决这个问题,或者我可以拆分我的模型。我想了解当前的行为,因为它与我对 ASP.NET MVC 4 和 WebApi 2 的预期和体验不同。
谢谢
最佳答案
简短的回答,当内容类型为 application/json 时,Newtonsoft Json.Net 用于反序列化 post/put 正文。因此,userId 和 listId 参数在反序列化期间被忽略,但在模型验证期间进行评估。
我删除了 JsonIgnore 属性以及所有数据注释,并更改为 FluentValidation 包,该包提供了在运行时配置如何根据调用类型验证正文的能力。
关于c# - 模型绑定(bind)忽略具有 JsonIgnore 属性的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56547247/