首页 > 编程语言 >ASP.NET Core教程-Model Binding(模型绑定)

ASP.NET Core教程-Model Binding(模型绑定)

时间:2022-11-27 09:11:06浏览次数:40  
标签:Core ASP name 模型 绑定 Binding used 参数 data

更新记录
转载请注明出处:
2022年11月27日 发布。
2022年11月25日 从笔记迁移到博客。

模型绑定是什么

模型绑定是指:使用来自HTTP请求的值来创建.NET对象的过程。

模型绑定的作用

自动实现控制器的参数与HTTP参数对应,无需手动去操作。

模型绑定的数据来源

默认情况下,模型绑定会在以下位置查找值:

  • 表单数据
  • 请求主体(仅[ApiController]修饰的控制器)
  • 路由段变量
  • 查询字符串

默认按从上到下的方式进行查找数据。

简单模型绑定

比如:字符串参数、布尔值参数、数值参数

直接使用方法的参数即可。没啥特别的。

复杂模型绑定

使用JSON的层次结构即可。

image

绑定集合和数组

比如这个接口

image

前端传参数的时候,注意命名即可。

image

指定模型绑定源

特性 描述
[FromForm] This attribute is used to select form data as the source of binding data. The name of the parameter is used to locate a form value by default, but this can be changed using the Name property, which allows a different name to be specified.
[FromRoute] This attribute is used to select the routing system as the source of binding data. The name of the parameter is used to locate a route data value by default, but this can be changed using the Name property, which allows a different name to be specified.
[FromQuery] This attribute is used to select the query string as the source of binding data. The name of the parameter is used to locate a query string value by default, but this can be changed using the Name property, which allows a different query string key to be specified.
[FromHeader] This attribute is used to select a request header as the source of binding data. The name of the parameter is used as the header name by default, but this can be changed using the Name property, which allows a different header name to be specified.
[FromBody] This attribute is used to specify that the request body should be used as the source of binding data, which is required when you want to receive data from requests that are not form-encoded, such as in API controllers that provide web services.

指定是否绑定

可以使用 [BindRequired] 修饰参数,表示必须绑定。

public class Customer
{
    //必须要绑定
    [BindRequired]
    public int Id { get; set; }
}

[Route("[controller]")]
public class ModelBindController : Controller
{
    [HttpPost]
    //使用类型作为参数
    public IActionResult Post(Customer customer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return Ok();
    }
}

可以使用 [[BindNever] 修饰参数,表示无需绑定。

[HttpPost]
//无需绑定
public IActionResult Post([BindNever][FromBody]Customer customer)
{
    //直接通过验证,IsValid = true,所以不会执行该代码
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    return Ok();
}

标签:Core,ASP,name,模型,绑定,Binding,used,参数,data
From: https://www.cnblogs.com/cqpanda/p/16921188.html

相关文章