问题描述
我不想在我的 CustomerViewModel 上绑定 Id 属性,所以我添加了一个 [BindNever] 属性,但它不起作用.有什么解决办法?
I do not want do bind the Id property on my CustomerViewModel so I added a [BindNever] attribute but it is not working. What could be the solution?
我有以下几点:
CustomerController.cs
// PUT api/customers/5
[HttpPut("{id}")]
public async Task<IActionResult> Put([FromUri] int id, [FromBody]CustomerViewModel customer)
{
//Implementation
}
客户视图模型
public class CustomerViewModel
{
[BindNever]
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
如果我输入以下 json .id 属性仍然被绑定
If I input the following json . The id property still gets binded
{
"id": 100,
"lastName": "Bruce",
"firstName": "Wayne",
"email": "bruce@gothamcity.com"
}
推荐答案
这个 博文读起来很有趣,并得出结论,[FromBody] 注释覆盖"了BindBehaviourAttribute(BindNever 是一个简单的特化).该模型由正文中的所有可用数据(在本例中为您的 JSON 数据)填充.
This Blog post is an interesting read and concludes that the [FromBody] annotation "overrides" the BindBehaviourAttribute (BindNever is a simple specialization). The model is populated by all data available from the body (your JSON data in this case).
我不认为这是直观的,issue 有一个很好的声明关于这个:
I do not consider this as intuitive, and the issue has a nice statement about this:
[BindRequired] 自定义MVC模型绑定系统.这就是它目的并按设计工作.
[BindRequired] customizes the MVC model binding system . That's its purpose and it's working as designed.
[FromBody] 将受影响的属性或参数切换到输入格式的不同世界.每个输入格式化程序(例如Json.NET 和一个小型的 MVC 特定包装器)可以被认为是一个具有自己定制的独立系统.模型绑定系统不知道 JSON(或任何其他)反序列化的细节.
[FromBody] switches the affected property or parameter into the different world of input formatting. Each input formatter (e.g. Json.NET and a small MVC-specific wrapper) can be considered a separate system with its own customization. The model binding system has no knowledge the details of JSON (or any other) deserialization.
经验教训:BindNever 在这种情况下不起作用.
Lesson learned: BindNever does not work in this scenario.
什么是替代品?
解决方案 1:编写一些自定义模型绑定代码.我自己没有做过,但是 在 MVC6 中创建自定义模型绑定器的正确方法是什么? 可能会有所帮助.
Solution 1: Writing some custom model binding code. I have not done it myself, but What is the correct way to create custom model binders in MVC6? may help.
解决方案 2:比较务实的解决方案
Solution 2: Rather pragmatic one
也许这个简单(但不是很好)的解决方法可以帮助您:
Perhaps this simple (but not very nice) workaround helps you out:
[HttpPut("{id}")]
public async Task<IActionResult> Put([FromUri] int id, [FromBody]CustomerViewModel customer)
{
customer.Id = 0;
//Implementation
}
这篇关于为什么 BindNever 属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)