ASP.NET Core教程-Model Binding(模型绑定)
更新记录
转载请注明出处:
2022年11月27日 发布。
2022年11月25日 从笔记迁移到博客。
模型绑定是什么
模型绑定是指:使用来自HTTP请求的值来创建.NET对象的过程。
模型绑定的作用
自动实现控制器的参数与HTTP参数对应,无需手动去操作。
模型绑定的数据来源
默认情况下,模型绑定会在以下位置查找值:
- 表单数据
- 请求主体(仅
[ApiController]
修饰的控制器) - 路由段变量
- 查询字符串
默认按从上到下的方式进行查找数据。
简单模型绑定
比如:字符串参数、布尔值参数、数值参数
直接使用方法的参数即可。没啥特别的。
复杂模型绑定
使用JSON的层次结构即可。
绑定集合和数组
比如这个接口
前端传参数的时候,注意命名即可。
指定模型绑定源
特性 | 描述 |
---|---|
[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();
}
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/16921188.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 全程不用写代码,我用AI程序员写了一个飞机大战