



























在 ASP.NET Core MVC 中,接收数据本质靠「模型绑定(Model Binding)」,根据数据来源和 Content-Type 不同,有多种标准写法。下面按最常见的使用场景系统梳理。
?id=1)public IActionResult GetUser(int id)
{
return Ok(id);
}
或显式声明:
public IActionResult GetUser([FromQuery] int id)
📌 适用于:GET请求
/user/1)[HttpGet("user/{id}")]
public IActionResult GetUser(int id)
{
return Ok(id);
}
显式写法:
public IActionResult GetUser([FromRoute] int id)
application/json)→ [FromBody]👉 前后端分离最常用
public record UserDto(string Name, int Age);
[HttpPost]
public IActionResult CreateUser([FromBody] UserDto user)
{
return Ok(user);
}
前端示例:
fetch('/api/user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'tom', age: 18 })
});
⚠️ 注意:
一个 Action 只能有一个 [FromBody]
必须是 application/json
application/x-www-form-urlencoded)public IActionResult Login([FromForm] string username, [FromForm] string password)
或绑定到模型:
public class LoginVm
{
public string Username { get; set; }
public string Password { get; set; }
}
[HttpPost]
public IActionResult Login(LoginVm vm)
📌 前端对应:
const params = new URLSearchParams();
params.append("username", "tom");
params.append("password", "123");
fetch("/login", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params
});
multipart/form-data)[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
using var stream = file.OpenReadStream();
多个文件:
public async Task<IActionResult> Upload(List<IFormFile> files)
配合 FormData:
const formData = new FormData();
formData.append("file", input.files[0]);
✅ 不能用 [FromBody]
[HttpPost("user/{id}")]
public IActionResult UpdateUser(
[FromRoute] int id,
[FromQuery] string source,
[FromBody] UserDto user)
|
特性 |
数据来源 |
常见 Content-Type |
|---|---|---|
|
默认 |
Query / Form |
- |
|
|
URL 路径 |
- |
|
|
URL 查询字符串 |
- |
|
|
Request Body |
|
|
|
Form 表单 |
|
|
|
请求头 |
- |
|
|
依赖注入 |
- |
可绑定到:
public string Name { get; set; }
{
"name": "Tom",
"skills": ["C#", "Java"]
}
public record UserDto(string Name, List<string> Skills);
IModelBinder
[ModelBinder(typeof(...))]
❌ JSON 用 [FromForm]
→ 永远拿不到值
❌ [FromBody]用两次
→ 运行时异常
❌ 文件上传却用 JSON
→ IFormFile为 null
✅ 想接表单又想接 JSON?
→ 不行,一个 Action 只能选一种 Body 绑定方式
|
场景 |
推荐方式 |
|---|---|
|
REST API |
|
|
传统 MVC 表单 |
默认绑定 / |
|
文件上传 |
|
|
GET 查询 |
|
|
RESTful 资源 |
|
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。