C#创建WebAPI的基础流程
使用C#创建WebAPI最主流的方式是通过ASP.NET Core框架实现,整个过程不需要复杂的配置,按照标准步骤操作即可完成基础接口的搭建。

1. 创建ASP.NET Core WebAPI项目
首先打开Visual Studio,选择创建新项目,在项目模板中搜索并选择ASP.NET Core Web API模板,点击下一步后设置项目名称和存储路径,框架选择.NET 6及以上版本,取消勾选启用OpenAPI支持(如果需要接口文档可以后续自行添加),点击创建即可生成基础项目。
2. 编写基础控制器
项目创建完成后,默认会生成一个WeatherForecastController示例控制器,我们可以参考这个结构编写自己的控制器。控制器需要继承自ControllerBase类,并且添加[ApiController]特性,同时设置路由规则。
下面是一个简单的基础控制器示例:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
// GET api/user
[HttpGet]
public IActionResult GetAllUsers()
{
var users = new[] { "张三", "李四", "王五" };
return Ok(users);
}
}
3. 启动项目测试接口
编写完成控制器后,直接启动项目,框架会自动启动内置的Kestrel服务器,默认端口通常是5000或者5001,在浏览器中访问https://localhost:5001/api/user,就可以看到返回的JSON格式的用户列表数据,说明基础的WebAPI已经创建成功。
C# WebAPI的几种常见用法
处理不同HTTP请求方法
WebAPI最常用的就是处理GET、POST、PUT、DELETE四种HTTP请求,分别对应查询、新增、修改、删除操作,通过不同的特性标注即可实现。
以下是处理四种请求的完整示例:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
// 模拟产品数据
private static List<Product> _products = new List<Product>
{
new Product { Id = 1, Name = "笔记本电脑", Price = 4999 },
new Product { Id = 2, Name = "无线鼠标", Price = 99 }
};
// GET api/product 查询所有产品
[HttpGet]
public IActionResult GetAllProducts()
{
return Ok(_products);
}
// GET api/product/1 根据ID查询单个产品
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// POST api/product 新增产品
[HttpPost]
public IActionResult AddProduct([FromBody] Product product)
{
product.Id = _products.Max(p => p.Id) + 1;
_products.Add(product);
// 返回201状态码,并指向新创建资源的地址
return CreatedAtAction(nameof(GetProductById), new { id = product.Id }, product);
}
// PUT api/product/1 修改产品
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, [FromBody] 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();
}
// DELETE api/product/1 删除产品
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
_products.Remove(product);
return NoContent();
}
}
// 产品实体类
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
参数绑定的常见用法
WebAPI中参数可以从不同位置获取,常见的有路由参数、查询参数、请求体参数,框架会自动完成参数绑定,不需要手动解析。
- 路由参数:通过[HttpGet("{参数名}")]的方式定义,如上面的GetProductById方法中的id参数,直接从路由中提取。
- 查询参数:直接在方法参数中定义,框架会自动从URL的查询字符串中匹配,比如/api/product?name=笔记本中的name参数。
- 请求体参数:使用[FromBody]特性标注,框架会自动将请求体的JSON数据反序列化为对应的实体类,如上面的AddProduct方法中的product参数。
查询参数的使用示例:
// GET api/product/search?keyword=笔记本&minPrice=1000
[HttpGet("search")]
public IActionResult SearchProducts(string keyword, decimal? minPrice)
{
var result = _products.Where(p =>
(string.IsNullOrEmpty(keyword) || p.Name.Contains(keyword)) &&
(!minPrice.HasValue || p.Price >= minPrice.Value)
).ToList();
return Ok(result);
}
返回结果格式处理
WebAPI默认返回JSON格式的数据,我们可以通过配置或者方法返回值调整返回格式。如果需要返回XML格式,可以在Program.cs中添加XML格式支持:
var builder = WebApplication.CreateBuilder(args);
// 添加XML格式支持
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
var app = builder.Build();
app.MapControllers();
app.Run();
之后在请求头中添加Accept: application/xml,接口就会返回XML格式的数据。
异常处理用法
实际开发中需要统一处理接口异常,避免直接返回框架默认的错误页面,可以通过中间件实现全局异常处理:
// Program.cs中添加异常处理中间件
var app = builder.Build();
// 全局异常处理中间件
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var errorResponse = new { code = 500, message = "服务器内部错误,请稍后重试" };
await context.Response.WriteAsJsonAsync(errorResponse);
});
});
app.MapControllers();
app.Run();
这样所有接口抛出的未处理异常都会被捕获,返回统一的JSON格式错误响应。
C#_WebAPIASP.NET_CoreRESTful_APIHTTP请求处理修改时间:2026-07-01 18:45:45