c# - 模型绑定(bind)忽略具有 JsonIgnore 属性的属性

标签 c# asp.net-core asp.net-core-mvc asp.net-core-webapi asp.net-core-3.0

我正在使用 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 提供的数据时,它不会填充 UserIdListId 字段。因此,模型绑定(bind)在验证期间失败并返回 HTTP 400,指出需要 UserIdListId

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"
}

如果我从模型的 UserIdListId 属性中删除 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/

相关文章:

c# - 如何在 DI 中注册自定义 UserStore 和 UserManager

c# - AutoMapper map Int

c# - 预加载 WPF DataGrid

c# - 在不指定默认值的情况下创建 'NOT NULL' SQLite 列

c# - 更改 ASP.NET Core Razor 页面中的默认路由

c# - 我无法调试 .NET Core 源代码

asp.net-core - ASP 核心 : how to route to API Controller that is located in the area folder?

c# - 无效的 il 代码 System.IO.Compression.ZipFile.OpenRead() 方法主体为空

google-chrome - 在开发人员中运行时未在 Google Chrome 中设置 ASP.net 核心身份验证 cookie

c# - 添加自定义标签助手