ASP.NET Core Web API 接口开发实战 从零构建高性能RESTful服务 深入中间件依赖注入与部署全流程

引言:现代Web API开发的最佳实践
在当今的微服务架构和前后端分离的开发模式中,ASP.NET Core Web API已经成为构建高性能后端服务的首选框架。它不仅提供了跨平台的能力,还通过其轻量级、模块化的设计带来了卓越的性能表现。本文将从零开始,详细讲解如何构建一个生产级别的RESTful服务,涵盖从项目创建到高级部署的完整流程。
我们将重点关注三个核心领域:
中间件管道的深度控制
、
依赖注入的最佳实践
以及
高性能部署策略
。无论你是初学者还是有经验的开发者,本文都将提供可立即应用的实战代码和架构建议。
一、项目初始化与架构设计
1.1 创建高性能项目模板
使用.NET CLI创建项目时,选择正确的模板至关重要。对于生产环境,我们推荐使用最小主机(Minimal Hosting)模型,它在.NET 6+中提供了更简洁的启动代码和更好的性能。
# 安装最新的.NET SDK(建议7.0或8.0)
dotnet –version

# 创建Web API项目(启用HTTPS和OpenAPI支持)
dotnet new webapi -n HighPerformanceApi –force
cd HighPerformanceApi

# 添加必要的包
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Swashbuckle.AspNetCore
dotnet add package Serilog.AspNetCore
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
1.2 项目结构与分层架构
为了保持代码的可维护性和可测试性,采用清晰的分层架构:
HighPerformanceApi/
├── Api/ # 入口层(Program.cs, Controllers)
├── Application/ # 业务逻辑层(Services, DTOs, Mappings)
├── Domain/ # 领域模型层(Entities, Enums, Interfaces)
├── Infrastructure/ # 基础设施层(Persistence, External Services)
└── Tests/ # 单元测试和集成测试
1.3 配置强类型配置模型
避免使用魔法字符串,创建强类型配置类:
// Application/Settings/DatabaseSettings.cs
public class DatabaseSettings
{
public string ConnectionString { get; set; } = string.Empty;
public int CommandTimeout { get; set; } = 30;
public int MaxPoolSize { get; set; } = 100;
}

// Application/Settings/JwtSettings.cs
public class JwtSettings
{
public string SecretKey { get; set; } = string.Empty;
public string Issuer { get; set; } = string.Empty;
public int ExpirationHours { get; set; } = 24;
}

// Program.cs 中绑定配置
var builder = WebApplication.CreateBuilder(args);

// 绑定强类型配置
builder.Services.Configure(
builder.Configuration.GetSection(“DatabaseSettings”));
builder.Services.Configure(
builder.Configuration.GetSection(“JwtSettings”));
二、依赖注入深度实践
2.1 理解服务生命周期
ASP.NET Core提供了三种主要的服务生命周期,正确选择对性能至关重要:
// Program.cs 或 Infrastructure/DependencyInjection.cs

public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
// 1. 瞬态(Transient)- 每次请求都创建新实例
// 适用于轻量级、无状态的服务
services.AddTransient();

// 2. 作用域(Scoped)- 每个HTTP请求创建一个实例
// 适用于数据库上下文、工作单元模式
services.AddScoped();
services.AddScoped();

// 3. 单例(Singleton)- 应用启动时创建,整个生命周期共享
// 适用于缓存、配置服务、日志记录器
services.AddSingleton();
services.AddSingleton();

return services;
}
}
2.2 构造函数注入 vs 方法注入
构造函数注入
是首选方式,因为它:
明确依赖关系
便于单元测试
保证对象创建时即具备完整功能
// 推荐:构造函数注入
[ApiController]
[Route(“api/[controller]”)]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
private readonly ILogger _logger;
private readonly IMapper _mapper;

public ProductsController(
IProductService productService,
ILogger logger,
IMapper mapper)
{
_productService = productService;
_logger = logger;
_mapper = mapper;
}

[HttpGet(“{id}”)]
public async Task> GetProduct(int id)
{
var product = await _productService.GetByIdAsync(id);
if (product == null)
return NotFound();

return Ok(_mapper.Map(product));
}
}
2.3 高级DI技巧:工厂模式与条件注册
// 根据配置动态选择实现
services.AddSingleton(provider =>
{
var config = provider.GetRequiredService();
var cacheType = config[“Cache:Type”];

return cacheType switch
{
“Redis” => new RedisCacheService(config.GetConnectionString(“Redis”)),
“InMemory” => new InMemoryCacheService(),
_ => new InMemoryCacheService()
};
});

// 作用域工厂模式
services.AddScoped(provider =>
{
var context = provider.GetRequiredService();
var logger = provider.GetRequiredService>();

return new Repository(context, logger);
});
三、中间件管道深度定制
3.1 理解中间件执行顺序
中间件的顺序至关重要,它决定了请求的处理流程:
// Program.cs
var app = builder.Build();

// 1. 异常处理中间件(必须在最前面)
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(“/error”);
app.UseHsts();
}

// 2. HTTPS重定向和HSTS
app.UseHttpsRedirection();
app.UseHsts();

// 3. 静态文件中间件(如果需要)
app.UseStaticFiles();

// 4. 路由中间件
app.UseRouting();

// 5. 认证和授权
app.UseAuthentication();
app.UseAuthorization();

// 6. 自定义中间件(注意顺序)
app.UseMiddleware();
app.UseMiddleware();
app.UseMiddleware();

// 7. 端点映射
app.MapControllers();
app.MapHealthChecks(“/health”);

app.Run();
3.2 自定义高性能中间件
创建一个用于请求日志和性能监控的中间件:
// Middleware/PerformanceMonitoringMiddleware.cs
public class PerformanceMonitoringMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public PerformanceMonitoringMiddleware(
RequestDelegate next,
ILogger logger)
{
_next = next;
_logger = logger;
}

public async Task InvokeAsync(HttpContext context)
{
// 记录请求开始时间
var stopwatch = Stopwatch.StartNew();
var originalBodyStream = context.Response.Body;

try
{
// 使用内存流来捕获响应体(用于日志)
using var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;

await _next(context);

stopwatch.Stop();

// 记录性能日志
if (stopwatch.ElapsedMilliseconds > 1000) // 超过1秒的请求
{
_logger.LogWarning(
“Slow request detected: {Method} {Path} took {Elapsed}ms”,
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds);
}

// 恢复响应流
memoryStream.Position = 0;
await memoryStream.CopyToAsync(originalBodyStream);
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(ex, “Request failed after {Elapsed}ms”, stopwatch.ElapsedMilliseconds);
throw;
}
finally
{
context.Response.Body = originalBodyStream;
}
}
}

// 扩展方法以便于注册
public static class PerformanceMonitoringMiddlewareExtensions
{
public static IApplicationBuilder UsePerformanceMonitoring(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
3.3 全局异常处理中间件
// Middleware/GlobalExceptionHandlerMiddleware.cs
public class GlobalExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public GlobalExceptionHandlerMiddleware(
RequestDelegate next,
ILogger logger)
{
_next = next;
_logger = logger;
}

public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, “An unhandled exception occurred”);

context.Response.ContentType = “application/json”;
context.Response.StatusCode = ex switch
{
UnauthorizedAccessException => StatusCodes.Status401Unauthorized,
KeyNotFoundException => StatusCodes.Status404NotFound,
ValidationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};

var errorResponse = new
{
error = ex.Message,
traceId = Activity.Current?.Id ?? context.TraceIdentifier,
timestamp = DateTime.UtcNow
};

await context.Response.WriteAsJsonAsync(errorResponse);
}
}
}
四、RESTful API设计最佳实践
4.1 资源设计与路由规范
// 正确的RESTful路由设计
[ApiController]
[Route(“api/[controller]”)] // 自动映射为 api/products
public class ProductsController : ControllerBase
{
// GET api/products – 获取所有产品(支持分页)
[HttpGet]
public async Task>> GetProducts(
[FromQuery] ProductParams param)
{
var products = await _productService.GetPagedAsync(param);
return Ok(products);
}

// GET api/products/5 – 获取单个产品
[HttpGet(“{id:int}”)]
public async Task> GetProduct(int id)
{
var product = await _productService.GetByIdAsync(id);
return product != null ? Ok(product) : NotFound();
}

// POST api/products – 创建产品
[HttpPost]
public async Task> CreateProduct(
[FromBody] CreateProductDto createDto)
{
var product = await _productService.CreateAsync(createDto);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}

// PUT api/products/5 – 完整更新
[HttpPut(“{id:int}”)]
public async Task UpdateProduct(int id, [FromBody] UpdateProductDto updateDto)
{
await _productService.UpdateAsync(id, updateDto);
return NoContent();
}

// PATCH api/products/5 – 部分更新
[HttpPatch(“{id:int}”)]
public async Task PatchProduct(int id, [FromBody] JsonPatchDocument patchDoc)
{
await _productService.PatchAsync(id, patchDoc);
return NoContent();
}

// DELETE api/products/5 – 删除产品
[HttpDelete(“{id:int}”)]
public async Task DeleteProduct(int id)
{
await _productService.DeleteAsync(id);
return NoContent();
}
}
4.2 DTO设计与验证
// Application/DTOs/ProductDto.cs
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
public int Stock { get; set; }
public DateTime CreatedAt { get; set; }
}

// Application/DTOs/CreateProductDto.cs
public class CreateProductDto
{
[Required(ErrorMessage = “产品名称不能为空”)]
[StringLength(100, MinimumLength = 2, ErrorMessage = “产品名称长度必须在2-100字符之间”)]
public string Name { get; set; } = string.Empty;

[Required]
[StringLength(500, ErrorMessage = “描述不能超过500字符”)]
public string Description { get; set; } = string.Empty;

[Range(0.01, 1000000, ErrorMessage = “价格必须在0.01到1000000之间”)]
public decimal Price { get; set; }

[Range(0, int.MaxValue, ErrorMessage = “库存不能为负数”)]
public int Stock { get; set; }
}

// Application/DTOs/UpdateProductDto.cs
public class UpdateProductDto
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;

[StringLength(500)]
public string Description { get; set; } = string.Empty;

[Range(0.01, 1000000)]
public decimal Price { get; set; }

[Range(0, int.MaxValue)]
public int Stock { get; set; }
}
4.3 分页与查询参数
// Application/DTOs/PaginationParams.cs
public class PaginationParams
{
private const int MaxPageSize = 50;
private int _pageSize = 10;

public int PageNumber { get; set; } = 1;

public int PageSize
{
get => _pageSize;
set => _pageSize = (value > MaxPageSize) ? MaxPageSize : value;
}
}

// Application/DTOs/ProductParams.cs 继承分页参数
public class ProductParams : PaginationParams
{
public string? SearchTerm { get; set; }
public string? SortBy { get; set; }
public bool Descending { get; set; } = false;
}

// Application/DTOs/PagedList.cs
public class PagedList : List
{
public int CurrentPage { get; private set; }
public int TotalPages { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }

public bool HasPrevious => CurrentPage > 1;
public bool HasNext => CurrentPage < TotalPages; public PagedList(List items, int count, int pageNumber, int pageSize)
{
CurrentPage = pageNumber;
PageSize = pageSize;
TotalCount = count;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
AddRange(items);
}

public static async Task> CreateAsync(
IQueryable source, int pageNumber, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageNumber – 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return new PagedList(items, count, pageNumber, pageSize);
}
}
五、Entity Framework Core 高性能实践
5.1 DbContext配置与连接池
// Infrastructure/Persistence/ApplicationDbContext.cs
public class ApplicationDbContext : DbContext, IApplicationDbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options) { }

public DbSet Products => Set();
public DbSet Categories => Set();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 配置索引
modelBuilder.Entity()
.HasIndex(p => p.Name)
.IsUnique()
.HasDatabaseName(“IX_Products_Name”);

modelBuilder.Entity()
.HasIndex(p => p.Price)
.HasDatabaseName(“IX_Products_Price”);

// 配置复合索引
modelBuilder.Entity()
.HasIndex(p => new { p.CategoryId, p.CreatedAt })
.HasDatabaseName(“IX_Products_Category_Created”);

// 配置默认值
modelBuilder.Entity()
.Property(p => p.CreatedAt)
.HasDefaultValueSql(“GETUTCDATE()”);

// 配置关系
modelBuilder.Entity()
.HasOne(p => p.Category)
.WithMany(c => c.Products)
.HasForeignKey(p => p.CategoryId)
.OnDelete(DeleteBehavior.Restrict);

base.OnModelCreating(modelBuilder);
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSqlServer(
connectionString,
options => options.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null))
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging(false); // 生产环境必须关闭
}
}
}

// Program.cs 配置DbContext与连接池
builder.Services.AddDbContext(options =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString(“DefaultConnection”),
sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
sqlOptions.CommandTimeout(60);
});

// 生产环境关闭敏感数据日志
if (builder.Environment.IsDevelopment())
{
options.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
}
});
5.2 高性能查询与NoTracking
// Application/Services/ProductService.cs
public class ProductService : IProductService
{
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;

public ProductService(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}

// 高性能查询:使用AsNoTracking提升只读查询性能
public async Task> GetPagedAsync(ProductParams param)
{
var query = _context.Products
.AsNoTracking() // 只读查询必须使用NoTracking
.Include(p => p.Category) // 预先加载关联数据
.Where(p => !p.IsDeleted) // 软删除过滤
.AsQueryable();

// 动态搜索
if (!string.IsNullOrEmpty(param.SearchTerm))
{
query = query.Where(p => p.Name.Contains(param.SearchTerm) ||
p.Description.Contains(param.SearchTerm));
}

// 动态排序
query = param.SortBy?.ToLower() switch
{
“price” => param.Descending ? query.OrderByDescending(p => p.Price) : query.OrderBy(p => p.Price),
“name” => param.Descending ? query.OrderByDescending(p => p.Name) : query.OrderBy(p => p.Name),
_ => param.Descending ? query.OrderByDescending(p => p.CreatedAt) : query.OrderBy(p => p.CreatedAt)
};

return await PagedList.CreateAsync(
query.ProjectTo(_mapper.ConfigurationProvider),
param.PageNumber,
param.PageSize);
}

// 高性能单条查询
public async Task GetByIdAsync(int id)
{
return await _context.Products
.AsNoTracking()
.Where(p => p.Id == id && !p.IsDeleted)
.ProjectTo(_mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
}

// 高性能批量操作
public async Task BulkUpdateStockAsync(IEnumerable productIds, int stockChange)
{
// 使用原始SQL进行批量更新,避免EF的变更跟踪开销
await _context.Database.ExecuteSqlRawAsync(
“UPDATE Products SET Stock = Stock + {0} WHERE Id IN ({1})”,
stockChange, string.Join(“,”, productIds));
}
}
5.3 异步编程模式
// 正确的异步编程模式
public async Task> CreateProductAsync(
[FromBody] CreateProductDto createDto)
{
// 验证数据
if (!ModelState.IsValid)
return BadRequest(ModelState);

// 映射到领域模型
var product = _mapper.Map(createDto);

// 异步保存
_context.Products.Add(product);
await _context.SaveChangesAsync();

// 异步返回结果
var productDto = _mapper.Map(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, productDto);
}

// 避免异步代码中的阻塞调用
// ❌ 错误:使用.Result或.Wait()
public ProductDto GetProduct(int id)
{
return _context.Products.FirstOrDefault(p => p.Id == id); // 阻塞调用
}

// ✅ 正确:使用async/await
public async Task GetProductAsync(int id)
{
return await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id);
}
六、性能优化与缓存策略
6.1 内存缓存实现
// Infrastructure/Caching/MemoryCacheService.cs
public class MemoryCacheService : ICacheService
{
private readonly IMemoryCache _cache;
private readonly ILogger _logger;
private readonly TimeSpan _defaultExpiration = TimeSpan.FromMinutes(10);

public MemoryCacheService(IMemoryCache cache, ILogger logger)
{
_cache = cache;
_logger = logger;
}

public async Task GetAsync(string key, Func> factory, TimeSpan? expiration = null)
{
if (_cache.TryGetValue(key, out T? cachedValue))
{
_logger.LogDebug(“Cache hit for key: {Key}”, key);
return cachedValue;
}

_logger.LogDebug(“Cache miss for key: {Key}”, key);
var value = await factory();

if (value != null)
{
var cacheOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(expiration ?? _defaultExpiration)
.RegisterPostEvictionCallback((k, v, r, s) =>
{
_logger.LogInformation(“Cache evicted: {Key} – Reason: {Reason}”, k, r);
});

_cache.Set(key, value, cacheOptions);
}

return value;
}

public void Remove(string key)
{
_cache.Remove(key);
_logger.LogDebug(“Cache removed for key: {Key}”, key);
}
}

// 在Controller中使用缓存
[ApiController]
[Route(“api/[controller]”)]
public class ProductsController : ControllerBase
{
private readonly ICacheService _cacheService;
private readonly IProductService _productService;

public ProductsController(ICacheService cacheService, IProductService productService)
{
_cacheService = cacheService;
_productService = productService;
}

[HttpGet(“{id}”)]
public async Task> GetProduct(int id)
{
var cacheKey = $”product:{id}”;

var product = await _cacheService.GetAsync(
cacheKey,
() => _productService.GetByIdAsync(id),
TimeSpan.FromMinutes(5));

if (product == null)
return NotFound();

return Ok(product);
}
}
6.2 分布式缓存(Redis)
// Infrastructure/Caching/RedisCacheService.cs
public class RedisCacheService : ICacheService
{
private readonly IConnectionMultiplexer _redis;
private readonly ILogger _logger;
private readonly IDatabase _database;

public RedisCacheService(IConnectionMultiplexer redis, ILogger logger)
{
_redis = redis;
_logger = logger;
_database = redis.GetDatabase();
}

public async Task GetAsync(string key, Func> factory, TimeSpan? expiration = null)
{
var cached = await _database.StringGetAsync(key);
if (cached.HasValue)
{
_logger.LogDebug(“Redis cache hit for key: {Key}”, key);
return JsonSerializer.Deserialize(cached!);
}

_logger.LogDebug(“Redis cache miss for key: {Key}”, key);
var value = await factory();

if (value != null)
{
var serialized = JsonSerializer.Serialize(value);
await _database.StringSetAsync(key, serialized, expiration ?? TimeSpan.FromMinutes(10));
}

return value;
}

public async Task RemoveByPatternAsync(string pattern)
{
var server = _redis.GetServer(_redis.GetEndPoints().First());
var keys = server.Keys(pattern: pattern).ToArray();

if (keys.Length > 0)
{
await _database.KeyDeleteAsync(keys);
_logger.LogInformation(“Removed {Count} cache keys matching pattern: {Pattern}”, keys.Length, pattern);
}
}
}

// Program.cs 配置Redis
builder.Services.AddSingleton(sp =>
{
var configuration = builder.Configuration.GetConnectionString(“Redis”);
return ConnectionMultiplexer.Connect(configuration);
});

builder.Services.AddSingleton();
6.3 响应缓存与ETag
// Middleware/ResponseCachingMiddleware.cs
public class ResponseCachingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public ResponseCachingMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}

public async Task InvokeAsync(HttpContext context)
{
// 只缓存GET请求
if (context.Request.Method != “GET”)
{
await _next(context);
return;
}

var cacheKey = $”response:{context.Request.Path}{context.Request.QueryString}”;
var cacheService = context.RequestServices.GetRequiredService();

// 尝试从缓存获取
var cachedResponse = await cacheService.GetAsync(
cacheKey,
async () =>
{
// 拦截响应流
var originalBodyStream = context.Response.Body;
using var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;

await _next(context);

memoryStream.Position = 0;
var responseBody = await new StreamReader(memoryStream).ReadToEndAsync();

// 恢复流
context.Response.Body = originalBodyStream;
await context.Response.WriteAsync(responseBody);

return responseBody;
},
TimeSpan.FromMinutes(5));

if (cachedResponse != null && context.Response.StatusCode == 200)
{
// 设置缓存相关的响应头
context.Response.Headers[“X-Cache”] = “HIT”;
context.Response.Headers[“Cache-Control”] = “public, max-age=300”;
}
}
}
七、日志与监控
7.1 Serilog配置与结构化日志
// Program.cs
using Serilog;

// 配置Serilog
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override(“Microsoft”, LogEventLevel.Warning)
.MinimumLevel.Override(“System”, LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithProperty(“Application”, “HighPerformanceApi”)
.WriteTo.Console(
outputTemplate: “[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}”)
.WriteTo.File(
“Logs/app-.log”,
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7,
outputTemplate: “{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}”)
.WriteTo.Seq(builder.Configuration[“Seq:ServerUrl”] ?? “http://localhost:5341”)
.CreateLogger();

builder.Host.UseSerilog(); // 替换默认日志提供程序

// 在控制器中使用结构化日志
[ApiController]
[Route(“api/[controller]”)]
public class ProductsController : ControllerBase
{
private readonly ILogger _logger;

public ProductsController(ILogger logger)
{
_logger = logger;
}

[HttpGet(“{id}”)]
public async Task> GetProduct(int id)
{
// 结构化日志
_logger.LogInformation(“Getting product {ProductId}”, id);

try
{
var product = await _productService.GetByIdAsync(id);
if (product == null)
{
_logger.LogWarning(“Product {ProductId} not found”, id);
return NotFound();
}

_logger.LogInformation(“Successfully retrieved product {ProductId}”, id);
return Ok(product);
}
catch (Exception ex)
{
_logger.LogError(ex, “Error getting product {ProductId}”, id);
return StatusCode(500, “Internal server error”);
}
}
}
7.2 健康检查
// Program.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;

builder.Services.AddHealthChecks()
.AddSqlServer(
builder.Configuration.GetConnectionString(“DefaultConnection”)!,
name: “SQL Database”,
failureStatus: HealthStatus.Unhealthy,
tags: new[] { “database”, “sql” })
.AddRedis(
builder.Configuration.GetConnectionString(“Redis”)!,
name: “Redis Cache”,
failureStatus: HealthStatus.Degraded,
tags: new[] { “cache”, “redis” })
.AddCheck(“Custom Check”, tags: new[] { “custom” });

// 自定义健康检查
public class CustomHealthCheck : IHealthCheck
{
public Task CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
// 检查系统资源、外部依赖等
var isHealthy = true; // 实际检查逻辑

return isHealthy
? Task.FromResult(HealthCheckResult.Healthy(“System is healthy”))
: Task.FromResult(HealthCheckResult.Unhealthy(“System is unhealthy”));
}
}

// 映射健康检查端点
app.MapHealthChecks(“/health”, new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{
context.Response.ContentType = “application/json”;
var result = new
{
status = report.Status.ToString(),
checks = report.Entries.Select(e => new
{
name = e.Key,
status = e.Value.Status.ToString(),
description = e.Value.Description,
duration = e.Value.Duration.TotalMilliseconds
})
};
await context.Response.WriteAsJsonAsync(result);
}
});
八、安全最佳实践
8.1 JWT认证与授权
// Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
var jwtSettings = builder.Configuration.GetSection(“JwtSettings”).Get()!;

options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Issuer, // 通常与Issuer相同
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
ClockSkew = TimeSpan.Zero // 精确控制令牌过期时间
};

// 事件处理
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add(“Token-Expired”, “true”);
}
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
// 自定义令牌验证逻辑
return Task.CompletedTask;
}
};
});

builder.Services.AddAuthorization(options =>
{
options.AddPolicy(“AdminOnly”, policy =>
policy.RequireRole(“Admin”));

options.AddPolicy(“RequireAuthenticatedUser”, policy =>
policy.RequireAuthenticatedUser());
});

// 创建Token的辅助类
public class JwtTokenService
{
private readonly JwtSettings _jwtSettings;

public JwtTokenService(IOptions jwtSettings)
{
_jwtSettings = jwtSettings.Value;
}

public string GenerateToken(string userId, string role)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, userId),
new Claim(ClaimTypes.Role, role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
issuer: _jwtSettings.Issuer,
audience: _jwtSettings.Issuer,
claims: claims,
expires: DateTime.UtcNow.AddHours(_jwtSettings.ExpirationHours),
signingCredentials: creds);

return new JwtSecurityTokenHandler().WriteToken(token);
}
}
8.2 输入验证与防SQL注入
// 使用参数化查询防止SQL注入
public async Task GetProductByDynamicQuery(int id)
{
// ❌ 危险:字符串拼接SQL
// var sql = $”SELECT * FROM Products WHERE Id = {id}”;
// return await _context.Products.FromSqlRaw(sql).FirstOrDefaultAsync();

// ✅ 安全:使用参数化查询
return await _context.Products
.FromSqlInterpolated($”SELECT * FROM Products WHERE Id = {id}”)
.FirstOrDefaultAsync();
}

// 自定义验证属性
public class PositiveAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is int intValue && intValue <= 0) { return new ValidationResult($"{validationContext.DisplayName} must be positive"); } if (value is decimal decimalValue && decimalValue <= 0) { return new ValidationResult($"{validationContext.DisplayName} must be positive"); } return ValidationResult.Success; } } // 在DTO中使用 public class CreateProductDto { [Required, StringLength(100, MinimumLength = 2)] public string Name { get; set; } = string.Empty; [Positive] public decimal Price { get; set; } [Range(0, int.MaxValue)] public int Stock { get; set; } } 8.3 CORS配置 // Program.cs builder.Services.AddCors(options =>
{
options.AddPolicy(“AllowSpecificOrigins”, policy =>
{
policy.WithOrigins(
“https://yourdomain.com”,
“https://app.yourdomain.com”)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders(“X-Custom-Header”, “Token-Expired”);
});

options.AddPolicy(“AllowAll”, policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});

// 在管道中使用
app.UseCors(“AllowSpecificOrigins”); // 在路由之前
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
九、测试策略
9.1 单元测试(xUnit + Moq)
// Tests/Unit/Services/ProductServiceTests.cs
public class ProductServiceTests
{
private readonly Mock _mockContext;
private readonly Mock _mockMapper;
private readonly ProductService _service;

public ProductServiceTests()
{
_mockContext = new Mock();
_mockMapper = new Mock();
_service = new ProductService(_mockContext.Object, _mockMapper.Object);
}

[Fact]
public async Task GetByIdAsync_ExistingId_ReturnsProduct()
{
// Arrange
var productId = 1;
var productEntity = new Product { Id = productId, Name = “Test Product” };
var productDto = new ProductDto { Id = productId, Name = “Test Product” };

var mockSet = new Mock>();
mockSet.As>()
.Setup(m => m.Provider)
.Returns(new TestAsyncEnumerable(new[] { productEntity }.AsQueryable()));

_mockContext.Setup(c => c.Products).Returns(mockSet.Object);
_mockMapper.Setup(m => m.Map(productEntity)).Returns(productDto);

// Act
var result = await _service.GetByIdAsync(productId);

// Assert
Assert.NotNull(result);
Assert.Equal(productId, result.Id);
}

[Fact]
public async Task GetByIdAsync_NonExistingId_ReturnsNull()
{
// Arrange
var mockSet = new Mock>();
mockSet.As>()
.Setup(m => m.Provider)
.Returns(new TestAsyncEnumerable(Enumerable.Empty().AsQueryable()));

_mockContext.Setup(c => c.Products).Returns(mockSet.Object);

// Act
var result = await _service.GetByIdAsync(999);

// Assert
Assert.Null(result);
}
}
9.2 集成测试
// Tests/Integration/ProductsControllerTests.cs
public class ProductsControllerTests : IClassFixture>
{
private readonly WebApplicationFactory _factory;

public ProductsControllerTests(WebApplicationFactory factory)
{
_factory = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
// 替换为测试数据库
services.AddDbContext(options =>
options.UseInMemoryDatabase(“TestDb”));
});
});
}

[Fact]
public async Task GetProduct_ReturnsSuccess()
{
// Arrange
var client = _factory.CreateClient();

// Act
var response = await client.GetAsync(“/api/products/1”);

// Assert
response.EnsureSuccessStatusCode();
var product = await response.Content.ReadFromJsonAsync();
Assert.NotNull(product);
}
}
十、部署与运维
10.1 Docker部署
# Dockerfile
# 使用多阶段构建优化镜像大小
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY [“HighPerformanceApi/HighPerformanceApi.csproj”, “HighPerformanceApi/”]
COPY [“Application/Application.csproj”, “Application/”]
COPY [“Domain/Domain.csproj”, “Domain/”]
COPY [“Infrastructure/Infrastructure.csproj”, “Infrastructure/”]
RUN dotnet restore “HighPerformanceApi/HighPerformanceApi.csproj”
COPY . .
WORKDIR “/src/HighPerformanceApi”
RUN dotnet build “HighPerformanceApi.csproj” -c Release -o /app/build

FROM build AS publish
RUN dotnet publish “HighPerformanceApi.csproj” -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY –from=publish /app/publish .

# 创建非root用户
RUN addgroup –group api –gid 1001 \
&& adduser –disabled-password –ingroup api –uid 1001 apiuser \
&& chown -R apiuser:api /app

USER apiuser

ENTRYPOINT [“dotnet”, “HighPerformanceApi.dll”]
10.2 docker-compose.yml
version: ‘3.8’

services:
api:
build:
context: .
dockerfile: Dockerfile
container_name: high-performance-api
ports:
– “5000:80”
– “5001:443”
environment:
– ASPNETCORE_ENVIRONMENT=Production
– ASPNETCORE_URLS=http://+:80
– ConnectionStrings__DefaultConnection=Server=sqlserver;Database=HighPerformanceApi;User=sa;Password=YourStrong!Passw0rd;TrustServerCertificate=true;
– ConnectionStrings__Redis=redis:6379
– Seq__ServerUrl=http://seq:5341
depends_on:
– sqlserver
– redis
– seq
restart: unless-stopped
networks:
– api-network

sqlserver:
image: mcr.microsoft.com/mssql/server:2022-latest
container_name: api-sqlserver
environment:
– ACCEPT_EULA=Y
– SA_PASSWORD=YourStrong!Passw0rd
– MSSQL_PID=Developer
ports:
– “1433:1433”
volumes:
– sqlserver-data:/var/opt/mssql
networks:
– api-network

redis:
image: redis:7-alpine
container_name: api-redis
ports:
– “6379:6379”
volumes:
– redis-data:/data
networks:
– api-network

seq:
image: datalust/seq:latest
container_name: api-seq
ports:
– “5341:5341”
environment:
– ACCEPT_EULA=Y
volumes:
– seq-data:/data
networks:
– api-network

networks:
api-network:
driver: bridge

volumes:
sqlserver-data:
redis-data:
seq-data:
10.3 生产环境配置
// appsettings.Production.json
{
“Logging”: {
“LogLevel”: {
“Default”: “Warning”,
“Microsoft.AspNetCore”: “Warning”,
“Microsoft.EntityFrameworkCore.Database.Command”: “Warning”
}
},
“ConnectionStrings”: {
“DefaultConnection”: “Server=sqlserver;Database=HighPerformanceApi;User=sa;Password=${DB_PASSWORD};TrustServerCertificate=true;MaxPoolSize=200;CommandTimeout=60”,
“Redis”: “redis:6379,abortConnect=false,connectTimeout=5000,asyncTimeout=5000”
},
“JwtSettings”: {
“SecretKey”: “${JWT_SECRET}”,
“Issuer”: “HighPerformanceApi”,
“ExpirationHours”: 24
},
“Seq”: {
“ServerUrl”: “http://seq:5341”
},
“Kestrel”: {
“Endpoints”: {
“Http”: {
“Url”: “http://*:80”
},
“Https”: {
“Url”: “https://*:443”,
“Certificate”: {
“Path”: “/app/certs/server.pfx”,
“Password”: “${CERT_PASSWORD}”
}
}
},
“Limits”: {
“MaxConcurrentConnections”: 100,
“MaxConcurrentUpgradedConnections”: 100,
“MaxRequestBodySize”: 52428800
}
},
“AllowedHosts”: “*”
}
10.4 Kubernetes部署清单
# k8s-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: high-performance-api
labels:
app: api
spec:
replicas: 3
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
– name: api
image: yourregistry/high-performance-api:latest
ports:
– containerPort: 80
env:
– name: ASPNETCORE_ENVIRONMENT
value: “Production”
– name: ConnectionStrings__DefaultConnection
valueFrom:
secretKeyRef:
name: api-secrets
key: database-connection
– name: ConnectionStrings__Redis
value: “redis-service:6379”
resources:
requests:
memory: “256Mi”
cpu: “250m”
limits:
memory: “512Mi”
cpu: “500m”
livenessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 5
periodSeconds: 5
—
apiVersion: v1
kind: Service
metadata:
name: api-service
spec:
type: LoadBalancer
ports:
– port: 80
targetPort: 80
protocol: TCP
selector:
app: api
—
apiVersion: v1
kind: Secret
metadata:
name: api-secrets
type: Opaque
data:
database-connection:
十一、性能监控与调优
11.1 应用性能监控(APM)
// Middleware/RequestTracingMiddleware.cs
public class RequestTracingMiddleware
{
private readonly RequestDelegate _next;

public RequestTracingMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
// 为每个请求创建唯一的TraceId
var traceId = Activity.Current?.Id ?? context.TraceIdentifier;
context.Response.Headers[“X-Trace-Id”] = traceId;

// 记录请求开始
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation(“Request started: {Method} {Path} TraceId: {TraceId}”,
context.Request.Method, context.Request.Path, traceId);

try
{
await _next(context);
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
“Request completed: {Method} {Path} {StatusCode} {Elapsed}ms TraceId: {TraceId}”,
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
stopwatch.ElapsedMilliseconds,
traceId);
}
}
}
11.2 性能调优检查清单
// 性能优化检查清单代码示例
public class PerformanceChecklist
{
// ✅ 使用异步API避免线程阻塞
public async Task GetProductAsync(int id)
{
return await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id);
}

// ✅ 使用AsNoTracking提升只读查询性能
public async Task> GetProductsAsync()
{
return await _context.Products
.AsNoTracking()
.ProjectTo(_mapper.ConfigurationProvider)
.ToListAsync();
}

// ✅ 使用投影避免加载不必要的数据
public async Task> GetProductNamesAsync()
{
return await _context.Products
.AsNoTracking()
.Select(p => new ProductNameDto { Id = p.Id, Name = p.Name })
.ToListAsync();
}

// ✅ 使用分页避免大数据集传输
public async Task> GetPagedProductsAsync(int page, int pageSize)
{
var query = _context.Products.AsNoTracking();
return await PagedList.CreateAsync(query, page, pageSize);
}

// ✅ 使用批量操作减少数据库往返
public async Task BulkUpdateStockAsync(Dictionary stockUpdates)
{
foreach (var batch in stockUpdates.Chunk(1000)) // 分批处理
{
var ids = batch.Select(x => x.Key).ToList();
await _context.Database.ExecuteSqlRawAsync(
“UPDATE Products SET Stock = Stock + CASE Id ” +
string.Join(” “, batch.Select((x, i) => $”WHEN {x.Key} THEN {x.Value}”)) +
” END WHERE Id IN ({0})”, string.Join(“,”, ids));
}
}

// ✅ 使用缓存减少重复计算
public async Task GetTotalRevenueAsync()
{
const string cacheKey = “total_revenue”;
return await _cacheService.GetAsync(
cacheKey,
async () => await _context.Orders.SumAsync(o => o.TotalAmount),
TimeSpan.FromHours(1));
}

// ✅ 使用连接池减少连接开销
public void ConfigureConnectionPool(IServiceCollection services, string connectionString)
{
services.AddDbContext(options =>
options.UseSqlServer(connectionString, sqlOptions =>
{
sqlOptions.EnableRetryOnFailure();
sqlOptions.CommandTimeout(60);
}));
}
}
十二、总结与最佳实践清单
12.1 核心性能优化清单
依赖注入
✅ 使用构造函数注入
✅ 正确选择生命周期(Transient/Scoped/Singleton)
✅ 避免循环依赖
✅ 使用工厂模式动态选择实现
中间件
✅ 异常处理中间件在最前
✅ 静态文件中间件在路由前
✅ 认证授权在路由前
✅ 自定义中间件注意顺序
数据库访问
✅ 只读查询使用AsNoTracking
✅ 使用投影避免加载不必要数据
✅ 使用分页处理大数据集
✅ 使用批量操作减少往返
✅ 配置连接池
缓存策略
✅ 内存缓存用于高频读取
✅ Redis用于分布式场景
✅ 设置合理的过期时间
✅ 实现缓存失效策略
异步编程
✅ 避免异步代码中的阻塞调用
✅ 使用async/await贯穿整个调用链
✅ 避免async void
✅ 使用ConfigureAwait(false)在库代码中
日志与监控
✅ 使用结构化日志
✅ 记录关键性能指标
✅ 实现健康检查
✅ 使用APM工具监控
安全
✅ 使用HTTPS
✅ 实施JWT认证
✅ 输入验证
✅ 防SQL注入
✅ CORS配置
部署
✅ 使用Docker容器化
✅ 多阶段构建优化镜像大小
✅ 使用环境变量管理配置
✅ 实现健康检查和就绪探针
✅ 配置资源限制
12.2 性能基准测试
// 使用BenchmarkDotNet进行性能测试
[MemoryDiagnoser]
public class PerformanceBenchmarks
{
private ApplicationDbContext _context;
private IMapper _mapper;

[GlobalSetup]
public void Setup()
{
var options = new DbContextOptionsBuilder()
.UseInMemoryDatabase(“BenchmarkDb”)
.Options;
_context = new ApplicationDbContext(options);

// 填充测试数据
for (int i = 1; i <= 1000; i++) { _context.Products.Add(new Product { Name = $"Product {i}", Price = i * 10, Stock = i * 5 }); } _context.SaveChanges(); var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap();
});
_mapper = config.CreateMapper();
}

[Benchmark]
public async Task> GetProductsWithTracking()
{
return await _context.Products
.ToListAsync();
}

[Benchmark]
public async Task> GetProductsWithNoTracking()
{
return await _context.Products
.AsNoTracking()
.ToListAsync();
}

[Benchmark]
public async Task> GetProductsWithProjection()
{
return await _context.Products
.AsNoTracking()
.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price
})
.ToListAsync();
}
}
通过本文的详细讲解和实战代码,你现在应该具备了构建高性能ASP.NET Core Web API的完整知识体系。记住,性能优化是一个持续的过程,需要结合实际业务场景进行权衡。建议从简单的优化开始,逐步深入,并始终通过性能测试来验证优化效果。
最后,保持代码的可读性和可维护性同样重要,不要为了微小的性能提升而过度复杂化代码结构。Happy coding! 🚀