ZetCode

ASP.NET ApiController

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 ApiController 属性。此属性对于构建 RESTful API 和 Web 服务至关重要。

ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。ApiController 通过内置功能简化了 API 开发。

基本定义

ASP.NET 中的 ApiController 属性将控制器标记为 Web API 控制器。它启用了惯用的行为,使构建 HTTP API 更加容易。

当应用于控制器类时,ApiController 启用自动模型状态验证、属性路由要求和默认响应格式化。

ApiController 是 ASP.NET Core MVC 框架的一部分。它专门用于构建具有 RESTful 约定和行为的 HTTP API。

ASP.NET ApiController 示例

以下示例演示了一个完整的 Web API,使用了 ApiController。

Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.Run();

这会设置一个基本的 ASP.NET 应用程序,并支持控制器。AddControllers 方法注册了控制器所需的服务。

Controllers/CustomersController.cs
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    private static List<Customer> _customers = new()
    {
        new Customer(1, "John", "Doe", "john@example.com"),
        new Customer(2, "Jane", "Smith", "jane@example.com"),
        new Customer(3, "Bob", "Johnson", "bob@example.com")
    };

    [HttpGet]
    public ActionResult<IEnumerable<Customer>> Get()
    {
        return _customers;
    }

    [HttpGet("{id}")]
    public ActionResult<Customer> GetById(int id)
    {
        var customer = _customers.FirstOrDefault(c => c.Id == id);
        if (customer == null) return NotFound();
        return customer;
    }

    [HttpPost]
    public IActionResult Create([FromBody] Customer customer)
    {
        customer.Id = _customers.Max(c => c.Id) + 1;
        _customers.Add(customer);
        return CreatedAtAction(nameof(GetById), new { id = customer.Id }, customer);
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, [FromBody] Customer customer)
    {
        var existing = _customers.FirstOrDefault(c => c.Id == id);
        if (existing == null) return NotFound();
        
        existing.FirstName = customer.FirstName;
        existing.LastName = customer.LastName;
        existing.Email = customer.Email;
        
        return NoContent();
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var customer = _customers.FirstOrDefault(c => c.Id == id);
        if (customer == null) return NotFound();
        
        _customers.Remove(customer);
        return NoContent();
    }
}

public record Customer(int Id, string FirstName, string LastName, string Email);

此控制器演示了一个完整的客户管理 CRUD API。ApiController 属性启用了一些自动行为。

该控制器继承自 ControllerBase,它提供了 HTTP 响应助手。Route 属性将基本路径设置为 /api/customers

该示例展示了所有主要的 HTTP 方法:GET 用于检索,POST 用于创建,PUT 用于更新,DELETE 用于删除。每种方法都返回适当的 HTTP 状态码。

ApiController 属性自动处理模型验证错误,并从不同源(路由、查询、正文)绑定参数。

来源

Microsoft ASP.NET Web API 文档

在本文中,我们探讨了 ASP.NET 8 中的 ApiController 属性。此强大功能通过内置约定简化了 API 开发。

作者

我叫 Jan Bodnar,是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 ASP.NET 教程