asp.net core api RESTful 风格控制器

发布于:2025-05-18 ⋅ 阅读:(17) ⋅ 点赞:(0)

在 ASP.NET Core API 中,遵循 RESTful 风格的控制器一般具备以下几个关键特征:

✅ RESTful 风格控制器的命名规范

控制器命名

  • 使用 复数名词,表示资源集合,如 ProductsControllerUsersController

路由风格

  • 路由使用 [Route("api/[controller]")],自动绑定控制器名。

  • 路由中不包含动词,操作由 HTTP 方法来表达。

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    // 示例方法如下
}

✅ RESTful 对应的 HTTP 方法与语义

HTTP 方法 路由示例 含义
GET /api/products 获取所有产品
GET /api/products/1 获取 ID 为 1 的产品
POST /api/products 新建产品
PUT /api/products/1 更新 ID 为 1 的产品
DELETE /api/products/1 删除 ID 为 1 的产品

✅ 示例控制器代码

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    // GET: api/products
    [HttpGet]
    public IActionResult GetAll()
    {
        var products = new List<string> { "Apple", "Banana", "Orange" };
        return Ok(products);
    }

    // GET: api/products/5
    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        var product = $"Product {id}";
        return Ok(product);
    }

    // POST: api/products
    [HttpPost]
    public IActionResult Create([FromBody] string product)
    {
        // 假设添加成功
        return CreatedAtAction(nameof(GetById), new { id = 123 }, product);
    }

    // PUT: api/products/5
    [HttpPut("{id}")]
    public IActionResult Update(int id, [FromBody] string product)
    {
        // 假设更新成功
        return NoContent();
    }

    // DELETE: api/products/5
    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        // 假设删除成功
        return NoContent();
    }
}

✅ RESTful 最佳实践

  1. 使用状态码准确表达结果

          200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found 等。
  2. 请求体与响应体结构统一

           推荐使用统一格式返回结果(如包裹成标准响应结构)。
  3. 避免在 URL 中加入动词

           错误示例:/api/getProductById/1
  4. 使用分页查询时,遵循统一格式

           /api/products?page=1&pageSize=10

网站公告

今日签到

点亮在社区的每一天
去签到