好的 👍 我来帮你系统整理一份 C# 进阶之 Web API 学习指南,包含概念、架构、核心技术点和示例代码。


🔹 C# 进阶之 Web API

1. 什么是 Web API?

ASP.NET Web API 是微软提供的一个框架,用于构建 基于 HTTP 的服务,支持:

  • 向浏览器、移动设备、桌面应用等提供数据服务
  • 使用 RESTful 风格(GET/POST/PUT/DELETE)
  • 默认使用 JSON 或 XML 作为数据交换格式

适合做 微服务接口移动端后端第三方接口开发


2. Web API 与 MVC 的区别

  • MVC:主要返回 视图(HTML 页面)
  • Web API:主要返回 数据(JSON、XML)
  • 两者底层相似,都基于 ASP.NET Pipeline,但关注点不同。

3. Web API 核心特性

  1. RESTful 风格接口
    • GET → 查询
    • POST → 新增
    • PUT → 修改
    • DELETE → 删除
  2. 模型绑定 & 验证:自动解析 JSON → C# 对象。
  3. 依赖注入(DI)支持:易扩展和测试。
  4. 过滤器(Filters):统一处理认证、日志、异常。
  5. 中间件(Middleware):自定义请求管道逻辑。
  6. 跨域(CORS):允许前端调用 API。

4. Web API 基本示例

创建一个简单 API(ASP.NET Core Web API)

using Microsoft.AspNetCore.Mvc;

namespace MyWebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductsController : ControllerBase
    {
        // 模拟数据
        private static readonly List<string> Products = new() { "手机", "电脑", "平板" };

        // GET api/products
        [HttpGet]
        public IActionResult GetProducts()
        {
            return Ok(Products);
        }

        // GET api/products/1
        [HttpGet("{id}")]
        public IActionResult GetProduct(int id)
        {
            if (id < 0 || id >= Products.Count) return NotFound();
            return Ok(Products[id]);
        }

        // POST api/products
        [HttpPost]
        public IActionResult AddProduct([FromBody] string product)
        {
            Products.Add(product);
            return CreatedAtAction(nameof(GetProduct), new { id = Products.Count - 1 }, product);
        }
    }
}


5. 高级特性(进阶)

✅ 路由(Routing)

[Route("api/v1/[controller]/[action]")]

支持 属性路由 和 约定路由

✅ 模型绑定 & 验证

public class UserDto
{
    [Required]
    public string Name { get; set; }

    [Range(1, 100)]
    public int Age { get; set; }
}

[HttpPost]
public IActionResult CreateUser([FromBody] UserDto user)
{
    if (!ModelState.IsValid) return BadRequest(ModelState);
    return Ok(user);
}

✅ 依赖注入(DI)

public interface IProductService
{
    IEnumerable<string> GetAll();
}

public class ProductService : IProductService
{
    public IEnumerable<string> GetAll() => new List<string> { "书籍", "笔记本" };
}

// Startup.cs / Program.cs
services.AddScoped<IProductService, ProductService>();

// Controller
private readonly IProductService _service;
public ProductsController(IProductService service) => _service = service;

✅ 过滤器(Filters)

public class LogActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context) 
        => Console.WriteLine("Action 执行前...");
    public void OnActionExecuted(ActionExecutedContext context) 
        => Console.WriteLine("Action 执行后...");
}

// 注册
services.AddControllers(options => options.Filters.Add<LogActionFilter>());

✅ 中间件(Middleware)

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    public RequestLoggingMiddleware(RequestDelegate next) => _next = next;

    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine($"请求路径: {context.Request.Path}");
        await _next(context);
    }
}

// Startup.cs
app.UseMiddleware<RequestLoggingMiddleware>();


6. Web API 安全性

  1. 身份认证:JWT / OAuth2 / OpenID Connect
  2. 授权:基于角色(Role)、策略(Policy)
  3. CORS:允许前端跨域访问services.AddCors(options => { options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); }); app.UseCors("AllowAll");

7. Web API 性能优化

  • 使用 分页缓存(MemoryCache/Redis)
  • 异步编程(async/await
  • 压缩(Gzip)
  • 使用 API Gateway(如 Ocelot)

8. 常见应用场景

  • 移动应用后台接口(iOS/Android)
  • Web 前后端分离(React/Vue + Web API)
  • 微服务架构接口
  • 第三方 API 平台(支付、物流、天气等)

👉 总结:
C# Web API 是进阶开发的核心技能,掌握它能让你轻松构建 高性能、可扩展、安全的 RESTful 服务,并支持多端调用。