【问题标题】:Model bind doesn't work in Asp.net Core 3.0模型绑定在 Asp.net Core 3.0 中不起作用
【发布时间】:2019-11-10 12:19:42
【问题描述】:

关注这篇文章https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.0

[Bind] attribute
Can be applied to a class or a method parameter. Specifies which properties of a model should be included in model binding.

In the following example, only the specified properties of the Instructor model are bound when any handler or action method is called:

C#

Copy
[Bind("LastName,FirstMidName,HireDate")]
public class Instructor
In the following example, only the specified properties of the Instructor model are bound when the OnPost method is called:

C#

Copy
[HttpPost]
public IActionResult OnPost([Bind("LastName,FirstMidName,HireDate")] Instructor instructor)
The [Bind] attribute can be used to protect against overposting in create scenarios. It doesn't work well in edit scenarios because excluded properties are set to null or a default value instead of being left unchanged.

我有一个模型定义为

public class Family
{
    public int ID { get; set; }
    public string Name { get; set; }

    public string Address { get; set; }
}

当我在 Web Api 控制器中使用它时,我希望输入的 faimly 模型只有 name 属性,但忽略 address 属性(null 或空)。 PostMan Json 身体:

 {
"Name": "Faimly1",
"Address":"Address1"
 }

    [HttpPost]
    public async Task<ActionResult<Family>> PostFamily([FromBody][Bind("Name")] Family family)
    {
        Console.WriteLine(family.Name); // Expect the string "Family1".
        Console.WriteLine(family.Address); // Should be empty even I have passed a string value.
    }

当我使用 Postman 测试操作时,我仍然得到 Address 值。 我应该怎么办?我在 asp.net core 3.0 和 asp.net core 2.1 中都对此进行了测试,并得到了相同的结果。

或者这个 Bind 只适用于标签助手?

【问题讨论】:

  • 也许试试 [Bind(Include = "Name")] 而不是 [Bind("Name")] ,看看它是否有帮助.
  • 我用了Bind(include:"Name"),还是不行。

标签: asp.net bind mode


【解决方案1】:

您可以尝试在模型类中使用JsonIgnoreAttribute,而不是BindAttribute:

public class Family
{
    public int ID { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public string Address { get; set; }
}

【讨论】:

  • 这是一个非常糟糕的技巧。如果 Web API 响应 XML 或 JSON 以外的其他格式怎么办?
  • 这不是一个决议。如果我将其转换为 json 字符串然后保存到文件中,JsonIgnore 会破坏内容。我更喜欢使用 JsonJgnore 以外的 ViewModel。但我只是想知道为什么 bind 不再起作用了?
猜你喜欢
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
相关资源
最近更新 更多