本文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控制器中使用此功能时,我期望输入模型仅具有name属性,而忽略address属性(空或空)。 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.
}
当我使用邮递员测试操作时,我仍然会获得“地址”值。 我该怎么办?我在asp.net core 3.0和asp.net core 2.1中都进行了测试,并获得了相同的结果。
还是此绑定仅与标签助手一起使用?
答案 0 :(得分:-1)
您可以尝试在模型类中使用JsonIgnoreAttribute代替BindAttribute:
public class Family
{
public int ID { get; set; }
public string Name { get; set; }
[JsonIgnore]
public string Address { get; set; }
}