为什么BindNever属性不起作用 [英] Why BindNever attribute doesn't work

查看:466
本文介绍了为什么BindNever属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想在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
}

CustomerViewModel

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

推荐答案

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).

我不认为这很直观,并且问题关于这个:

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:更加务实

也许这种简单(但不是很好)的解决方法可以帮助您:

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属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆