为什么使用 ASP.NET 核心模型绑定属性?

Why use ASP.NET Core modelbinding attributes?

为什么我们应该在 ASP.NET 核心模型绑定中应用这些属性?

不使用它们会有什么后果?

模型绑定引擎是否能够搜索传入的请求并将它们映射到没有这些属性的控制器操作方法参数:

查看此控制器操作方法示例:

public ActionResult<Pet> Create([FromBody] Pet pet)

public ActionResult<List<Pet>> Search([FromRoute] string breed, [FromQuery] string color, [FromQuery] int age)

我们也可以将属性应用于模型class:

public class Pet
{
    public string Name { get; set; }

    [FromQuery]
    public string Breed { get; set; }
}

来源:Microsoft Docs

没有属性的控制器操作方法示例:

public ActionResult<Pet> Create(Pet pet)

public ActionResult<List<Pet>> Search(string breed, string color, int age)

您可以查看 Sources 描述:

默认情况下,模型绑定在 HTTP 请求中从以下来源获取 key-value 对形式的数据:

  1. 表单字段
  2. 请求body(对于具有 [ApiController] 属性的控制器。)
  3. 路由数据
  4. 查询字符串参数
  5. 已上传文件

对于每个目标参数或 属性,将按照前面列表中指示的顺序扫描源。如果默认来源不正确,我们可以使用以下属性之一来指定来源:

  • [FromQuery] - 从查询字符串中获取值。
  • [FromRoute] - 从路线数据中获取值。
  • [FromForm] - 从已发布的表单字段中获取值。
  • [FromBody] - 从请求中获取值 body.
  • [FromHeader] - 从 HTTP headers.
  • 获取值

例如:

使用以下方法时,会从表单域中获取宠物数据:

public ActionResult<Pet> Create(Pet pet)

如果使用下面的方法,会从默认源中获取参数。我们可以通过表单或查询字符串传递参数。

public ActionResult<List<Pet>> Search(string breed, string color, int age)

如果给上面的方法添加属性,像这样:

public ActionResult<List<Pet>> Search([FromQuery]string breed, [FromQuery]string color, [FromQuery]int age)

您只能通过查询字符串传递参数。在这种情况下,如果通过Form传递参数,action方法中的参数将是Null.

因此,通过使用这些属性,我们可以指定模型绑定源,而无需扫描默认源列表。