ASP.NET Core怎么创建Web API ASP.NET Core创建RESTful API步骤

来源:这里教程网 时间:2026-02-21 17:33:59 作者:

ASP.NET Core 创建 Web API 很简单,核心是用 Controller + [ApiController] 特性 + 模型绑定 + 内置 JSON 序列化,不需要额外装包(.NET 6+ 默认内置)。

1. 新建 ASP.NET Core Web API 项目

用 CLI 或 Visual Studio 都行,推荐命令行快速启动:

dotnet new webapi -n MyApi —— 创建带 WeatherForecast 示例的模板 cd MyApi && dotnet run —— 启动后访问
https://localhost:5001/weatherforecast
就能看到默认 API

注意:.NET 6+ 模板默认启用 minimal hosting 模式(Program.cs 里一行 builder.Build()),但 Controller 方式仍完全支持,无需改写。

2. 添加自己的 API Controller

右键项目 → 添加 → 新建控制器 → 选择 “API Controller with actions, using Entity Framework”(如果连数据库)或 “API Controller – Empty”(纯接口)。

给类加上
[ApiController]
[Route("api/[controller]")]
方法用 HTTP 方法特性标记,比如
[HttpGet]
[HttpPost]
返回类型建议用
IActionResult
或具体模型(如
Task<ienumerable>></ienumerable>
),框架会自动序列化为 JSON

示例:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok(new[] { new { Id = 1, Name = "Laptop" } });
    [HttpPost]
    public IActionResult Create([FromBody] Product product)
    {
        // 处理逻辑
        return CreatedAtAction(nameof(Get), new { id = 1 }, product);
    }
}

3. 启用并配置 JSON 序列化(可选但常用)

.NET 6+ 默认用 System.Text.Json,若需兼容旧习惯(如驼峰命名、忽略 null 值),在

Program.cs
中配置:

builder.Services.AddControllers().AddJsonOptions(opt => { opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }); 如需支持循环引用或 DateTime 格式控制,也可在这里设
ReferenceHandler
Converters

4. 启用 CORS(跨域调试时必需)

前端调用本地 API 时浏览器会拦截,加一段配置即可:

Program.cs
中添加服务:builder.Services.AddCors();
在中间件中启用:app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); 生产环境请替换
AllowAnyOrigin()
为具体域名

基本上就这些。不复杂但容易忽略路由匹配、模型绑定失败静默返回 400、以及没开 CORS 导致前端收不到响应——检查这几个点,API 就能稳稳跑起来。

相关推荐