跳到主要内容

ASP.NET Core Controller

Controller(控制器)就是 Web API 的“接待员”:接收 HTTP 请求,调用业务逻辑,然后返回 HTTP 响应。

1. Controller 在哪里工作

一次典型请求:

GET /api/products/1

ASP.NET Core 路由匹配

ProductsController.GetById(1)

查询数据或调用 Service

返回 200 + JSON

Controller 通常负责:

  • 接收 URL、查询参数和 JSON 请求体
  • 判断应该执行哪个 Action 方法
  • 调用 Service 或数据库操作
  • 返回状态码和 JSON 数据

ASP.NET Core 同时支持 Minimal API 和 Controller API。Controller 更适合接口较多、业务较复杂、需要清晰分层的项目。参考 微软 Controller Web API 教程

2. 最简单的 Controller

using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
var products = new[]
{
new { Id = 1, Name = "键盘", Price = 299 },
new { Id = 2, Name = "鼠标", Price = 99 }
};

return Ok(products);
}
}

请求:

GET /api/products

返回:

[
{
"id": 1,
"name": "键盘",
"price": 299
},
{
"id": 2,
"name": "鼠标",
"price": 99
}
]

3. 逐行理解

[ApiController]

[ApiController]

告诉 ASP.NET Core:这是一个 Web API 控制器。

它还会提供一些自动行为,例如:

  • 自动推断参数来自 URL 还是请求体
  • 模型验证失败时自动返回 400 Bad Request
  • 使用更标准的 API 错误响应格式

参考 ApiController 官方说明

[Route("api/[controller]")]

[Route("api/[controller]")]

定义 Controller 的基础地址。[controller] 会去掉类名的 Controller 后缀:

ProductsController → products

所以基础地址是:

/api/products

ControllerBase

public class ProductsController : ControllerBase

Web API Controller 通常继承 ControllerBase。它提供了很多返回 HTTP 响应的方法:

Ok(data); // 200
Created(...); // 201
BadRequest(...); // 400
Unauthorized(); // 401
NotFound(); // 404
NoContent(); // 204

Controller 则额外包含 MVC View 页面功能。只做 Web API 时,通常使用 ControllerBase

[HttpGet]

[HttpGet]

表示这个方法处理 HTTP GET 请求。这个方法也叫做 Action

public IActionResult GetAll()

因此 GET /api/products 会调用 GetAll()

4. 根据 ID 查询

[HttpGet("{id:int}")]
public IActionResult GetById(int id)
{
if (id != 1)
{
return NotFound(new { Message = "商品不存在" });
}

var product = new
{
Id = 1,
Name = "键盘",
Price = 299
};

return Ok(product);
}

请求:

GET /api/products/1

路由模板中的 "{id:int}" 表示 URL 中必须提供一个整数参数,ASP.NET Core 会把 URL 中的 1 自动绑定给方法参数 int id

如果商品不存在,return NotFound(); 会返回状态码 404 Not Found

5. 接收 POST JSON

先定义模型:

public class CreateProductRequest
{
public string Name { get; set; } = string.Empty;

public decimal Price { get; set; }
}

Controller 中添加:

[HttpPost]
public IActionResult Create(CreateProductRequest request)
{
var product = new
{
Id = 3,
request.Name,
request.Price
};

return CreatedAtAction(
nameof(GetById),
new { id = product.Id },
product
);
}

客户端请求:

POST /api/products
Content-Type: application/json

请求体:

{
"name": "显示器",
"price": 1299
}

ASP.NET Core 会自动把 JSON 转换成 CreateProductRequest request,这叫做 模型绑定(Model Binding)

CreatedAtAction() 会返回 201 Created,并在 Location 响应头中指出新资源的访问地址。

6. Program.cs 必须注册 Controller

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();

app.MapControllers();

app.Run();

两句最关键:

  • builder.Services.AddControllers(); 注册 Controller 相关服务。
  • app.MapControllers(); 把 Controller 的路由添加到应用中。

缺少其中任何一句,Controller 都可能无法正常访问。

7. HTTP 方法与 CRUD

HTTP 方法Controller 特性常见用途
GET[HttpGet]查询数据
GET[HttpGet("{id}")]根据 ID 查询
POST[HttpPost]新增数据
PUT[HttpPut("{id}")]完整更新
PATCH[HttpPatch("{id}")]部分更新
DELETE[HttpDelete("{id}")]删除数据

例如:

[HttpDelete("{id:int}")]
public IActionResult Delete(int id)
{
// 删除数据

return NoContent();
}

成功后返回 204 No Content

8. 初学阶段先掌握这些

建议按这个顺序学习:

  1. Controller、Action 是什么
  2. [Route][HttpGet]
  3. URL 参数和查询参数
  4. POST JSON 请求体
  5. IActionResult 和 HTTP 状态码
  6. Model、DTO 和模型验证
  7. Controller 调用 Service
  8. Service 调用 EF Core 数据库

核心结构可以先记住:

[ApiController]
[Route("api/[controller]")]
public class XxxController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok();
}
}

初学时尤其注意:Controller 应该保持轻量,复杂业务逻辑通常放在 Service 中,而不是全部堆在 Controller 里。