ASP.NET Core 进阶
2024/2/1大约 3 分钟
ASP.NET Core 进阶
概述
ASP.NET Core 是一个跨平台、高性能的开源框架,用于构建现代化的 Web 应用程序。本文将深入探讨 ASP.NET Core 的高级特性和最佳实践。
1. 依赖注入深度解析
1.1 服务生命周期
ASP.NET Core 支持三种服务生命周期:
// 瞬时服务 - 每次请求创建新实例
services.AddTransient<ITransientService, TransientService>();
// 作用域服务 - 每个请求范围内共享一个实例
services.AddScoped<IScopedService, ScopedService>();
// 单例服务 - 整个应用生命周期内共享一个实例
services.AddSingleton<ISingletonService, SingletonService>();1.2 构造函数注入
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IMyService _service;
// 构造函数注入
public HomeController(ILogger<HomeController> logger, IMyService service)
{
_logger = logger;
_service = service;
}
}1.3 自定义服务容器
public void ConfigureServices(IServiceCollection services)
{
// 添加自定义服务
services.AddTransient<IMyService, MyService>();
// 使用工厂模式创建服务
services.AddSingleton<IMyFactory>(sp =>
{
var config = sp.GetRequiredService<IConfiguration>();
return new MyFactory(config["MySetting"]);
});
}2. 中间件开发
2.1 自定义中间件
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 请求处理前的逻辑
Console.WriteLine("请求到达");
// 调用下一个中间件
await _next(context);
// 请求处理后的逻辑
Console.WriteLine("请求完成");
}
}
// 扩展方法
public static class CustomMiddlewareExtensions
{
public static IApplicationBuilder UseCustomMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomMiddleware>();
}
}2.2 在 Startup 中使用
public void Configure(IApplicationBuilder app)
{
app.UseCustomMiddleware();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}3. 路由高级配置
3.1 属性路由
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<Product>> Get() { ... }
[HttpGet("{id:int}")]
public ActionResult<Product> GetById(int id) { ... }
[HttpGet("search")]
public ActionResult<IEnumerable<Product>> Search([FromQuery] string keyword) { ... }
}3.2 自定义路由约束
public class SlugRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route,
string routeKey, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (values.TryGetValue(routeKey, out var value) && value is string slug)
{
return slug.All(c => char.IsLower(c) || char.IsDigit(c) || c == '-');
}
return false;
}
}
// 注册约束
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("slug", typeof(SlugRouteConstraint));
});
}4. 性能优化
4.1 响应缓存
[HttpGet]
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public ActionResult<IEnumerable<Product>> Get() { ... }4.2 输出缓存(.NET 7+)
[HttpGet]
[OutputCache(Duration = 60)]
public ActionResult<IEnumerable<Product>> Get() { ... }4.3 内存缓存
public class MyService
{
private readonly IDistributedCache _cache;
public MyService(IDistributedCache cache)
{
_cache = cache;
}
public async Task<string> GetCachedDataAsync(string key)
{
var cached = await _cache.GetStringAsync(key);
if (cached != null)
return cached;
// 获取数据并缓存
var data = await FetchDataFromDatabase();
await _cache.SetStringAsync(key, data, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)
});
return data;
}
}5. 错误处理与日志
5.1 全局异常处理
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error");
app.UseHsts();
}
}
// 错误控制器
[ApiController]
[Route("/error")]
public class ErrorController : ControllerBase
{
[HttpGet]
public ActionResult<ErrorResponse> GetError()
{
var exceptionHandlerPathFeature =
HttpContext.Features.Get<IExceptionHandlerPathFeature>();
return Problem(
detail: exceptionHandlerPathFeature?.Error.Message,
title: "An error occurred"
);
}
}5.2 结构化日志
public class MyService
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public void Process(int id, string name)
{
_logger.LogInformation("Processing item {Id} with name {Name}", id, name);
try
{
// 业务逻辑
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process item {Id}", id);
throw;
}
}
}6. 配置管理
6.1 强类型配置
public class MySettings
{
public string ApiKey { get; set; }
public int Timeout { get; set; }
public DatabaseSettings Database { get; set; }
}
public class DatabaseSettings
{
public string ConnectionString { get; set; }
public string Provider { get; set; }
}
// 绑定配置
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MySettings>(Configuration.GetSection("MySettings"));
}
// 使用配置
public class MyService
{
private readonly MySettings _settings;
public MyService(IOptions<MySettings> settings)
{
_settings = settings.Value;
}
}6.2 环境特定配置
appsettings.json # 基础配置
appsettings.Development.json # 开发环境
appsettings.Staging.json # 测试环境
appsettings.Production.json # 生产环境总结
ASP.NET Core 提供了丰富的高级特性,包括依赖注入、中间件、路由、缓存、日志等。掌握这些进阶知识对于构建高质量的企业级应用至关重要。
作者:Blogger
日期:2024年2月1日