1

按照这篇文章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 或空)。邮递员 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 中都对此进行了测试,得到了相同的结果。

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

4

1 回答 1

-1

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

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

    [JsonIgnore]
    public string Address { get; set; }
}
于 2019-11-10T15:27:23.867 回答