使用ASP.NET Core创建RESTful API:安装.NET SDK后,通过dotnet new webapi命令创建项目,定义Product模型和ProductsController实现CRUD操作,运行dotnet run启动服务,访问https://localhost:5001/swagger测试接口,可选集成Entity Framework Core支持数据库,并通过dotnet publish部署应用。

要使用 C# 创建一个 RESTful API,最常用的方式是通过 ASP.NET Core。它轻量、跨平台,并且非常适合构建现代 Web API。下面是一个完整的入门教程,带你从零开始创建一个简单的 RESTful API。
1. 准备开发环境
确保你已安装以下工具:
- .NET SDK(建议 6.0 或更高版本)
- Visual Studio(2022 推荐)或 Visual Studio Code
- 终端/命令行工具
你可以通过运行 dotnet --version 检查是否已安装 .NET SDK。
2. 创建 Web API 项目
打开终端,执行以下命令创建一个新的 Web API 项目:
dotnet new webapi -n MyRestApicd MyRestApi
dotnet run
项目创建完成后,默认会在 http://localhost:5000 启动服务,访问 https://localhost:5001/weatherforecast 可看到示例数据。
3. 理解项目结构
关键文件和目录说明:
- Program.cs:应用入口,配置服务和中间件(.NET 6+ 使用隐式 using 和顶级语句)
- Controllers 文件夹:存放控制器类,处理 HTTP 请求
- appsettings.json:配置文件,如数据库连接字符串
- Properties/launchSettings.json:本地运行配置
4. 创建自己的数据模型
添加一个表示“产品”的类:
public class Product{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
将这个类保存在项目根目录下,命名为 Product.cs。
5. 创建控制器处理请求
新建控制器 ProductsController.cs:
using Microsoft.AspNetCore.Mvc;[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List
{
new Product { Id = 1, Name = "键盘", Price = 299 },
new Product { Id = 2, Name = "鼠标", Price = 99 }
};
[HttpGet]
public IActionResult Get() => Ok(_products);
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
return product == null ? NotFound() : Ok(product);
}
[HttpPost]
public IActionResult Post(Product product)
{
product.Id = _products.Max(p => p.Id) + 1;
_products.Add(product);
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public IActionResult Put(int id, Product updatedProduct)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
product.Name = updatedProduct.Name;
product.Price = updatedProduct.Price;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
_products.Remove(product);
return NoContent();
}
}
这个控制器实现了标准的 CRUD 操作:
- GET /api/products → 获取所有产品
- GET /api/products/1 → 获取特定产品
- POST /api/products → 添加新产品
- PUT /api/products/1 → 更新产品
- DELETE /api/products/1 → 删除产品
6. 测试你的 API
启动服务:
本文档主要讲述的是CXF创建webservice服务端;Apache CXF是一个开源的 Services框架,CXF帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spri
使用工具测试 API:
- 浏览器访问 https://localhost:5001/api/products
- 使用 Postman 或 curl 发送 POST、PUT、DELETE 请求
- VS Code 安装 Thunder Client 插件进行测试
7. 添加数据库支持(可选)
若需要持久化存储,可集成 Entity Framework Core:
dotnet add package Microsoft.EntityFrameworkCore.SqlServerdotnet add package Microsoft.EntityFrameworkCore.Tools
然后定义 DbContext:
public class AppDbContext : DbContext{
public DbSet
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyAppDb;Trusted_Connection=true;");
}
再在 Program.cs 中注册上下文:
builder.Services.AddDbContext8. 启用 Swagger 文档
ASP.NET Core 模板默认已集成 Swagger(也叫 OpenAPI)。运行项目后访问:
https://localhost:5001/swagger你可以在浏览器中查看和测试所有 API 接口。
9. 部署 API
发布项目到生产环境:
dotnet publish -c Release -o ./publish然后将 publish 文件夹部署到 IIS、Docker、Azure 或 Linux 服务器上。
基本上就这些。你现在拥有了一个功能完整的 C# RESTful API,支持标准 HTTP 方法、JSON 数据交换,并具备扩展能力。后续可以加入身份验证(JWT)、日志记录、异常处理、CORS 配置等高级功能。









