ASP.NET Core 的 BindNever 不适用于记录

ASP.NET Core's BindNever does not work with record

提问人:lonix 提问时间:11/13/2023 最后编辑:lonix 更新时间:11/13/2023 访问量:38

问:

使用 Razor Pages 7 时,我在代码隐藏文件中有这个:

public record PersonDto(
  long Id,
  string Name,
  [BindNever] string Address,
  // ...
);

[BindProperty] public PersonDto Person { get; set; }

我将其填充并在页面上显示。我在更新数据库中阅读了它。OnGet()OnPost()

但应该是只读的。我不允许更改它,因此 post 处理程序总是失败并显示验证错误 。Address"The Address field is required"

该属性在记录中不起作用(即使文档显示它应该起作用)。BindNever

我还尝试了长格式记录语法和语法,结果相同。[property:BindNever]

有人知道为什么吗?

asp.net-core razor-pages 模型绑定 asp.net-core-7.0 c# 记录类型

评论


答:

0赞 lonix 11/13/2023 #1

我找到了一个解决方法。我替换了这个:

[BindNever] string Address,

有了这个:

[property:BindNever] string? Address,

评论

1赞 Mike Brind 11/13/2023
您可能仍希望将该特性添加到可为 null 的属性中,以防止过度发布攻击。[BindNever]
0赞 lonix 11/13/2023
@MikeBrind谢谢迈克。知道为什么仅凭属性是不够的吗?在模型绑定文档页中,它显示它正在记录中使用。另外,我认为我需要使用 .[property:BindNever]
0赞 lonix 11/13/2023
更新了答案。
1赞 Mike Brind 11/13/2023
如果启用可为 null 的上下文,则模型绑定程序会将不可为 null 的字符串视为必需:learn.microsoft.com/en-us/aspnet/core/mvc/models/...