如何在ASP.NET Core 5.0 Web API中实现DelegatingHandler
ASP.NET Core 5.0 Web API 实现 DelegatingHandler 正确步骤
首先明确版本差异:旧版 ASP.NET Web API 中 DelegatingHandler 可直接用于处理入站 API 请求,ASP.NET Core 体系中入站请求处理统一使用中间件,DelegatingHandler 仅作用于 HttpClient 的出站请求管道。你编写的AuthenticationHandler代码本身是符合要求的,可按以下步骤配置使用:
前置场景判断
- 若你需要处理外部客户端发送到你的 Web API 的入站请求:直接改用中间件实现即可,不需要使用 DelegatingHandler
- 若你需要处理你的 Web API 内部调用第三方接口时的 HttpClient 出站请求/响应:继续按后续步骤配置即可
你提供的解决方案文件结构如下:
步骤1:注册自定义 DelegatingHandler
打开项目中的Startup.cs文件,在ConfigureServices方法中完成服务注册:
public void ConfigureServices(IServiceCollection services) { // 注册自定义 DelegatingHandler,生命周期设为 Transient services.AddTransient<AuthenticationHandler>(); // 注册 HttpClient 并绑定自定义 Handler 到它的执行管道 services.AddHttpClient("自定义HttpClient名称", client => { // 可在此配置 HttpClient 通用参数,比如默认请求地址 client.BaseAddress = new Uri("https://你的目标接口域名/"); }) .AddHttpMessageHandler<AuthenticationHandler>(); // 将自定义 Handler 加入管道 // 你的其他原有服务注册逻辑 services.AddControllers(); }
如果需要让该 Handler 作用于项目内所有 HttpClient,可改为:
services.AddHttpClientAll().AddHttpMessageHandler<AuthenticationHandler>();
步骤2:使用绑定了 Handler 的 HttpClient
在需要发起外部请求的控制器或业务服务中,注入IHttpClientFactory,用之前配置的名称创建 HttpClient 即可,所有请求/响应都会自动经过你的AuthenticationHandler处理:
[ApiController] [Route("[controller]")] public class DemoController : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; public DemoController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } [HttpGet] public async Task<IActionResult> TestRequest() { // 用你之前配置的名称创建 HttpClient var client = _httpClientFactory.CreateClient("自定义HttpClient名称"); var response = await client.GetAsync("目标接口路径"); return Ok(response.StatusCode); } }
入站请求场景替代方案(中间件实现)
如果你是要实现旧版 Web API 中 DelegatingHandler 处理入站请求的效果,直接把逻辑改写为中间件即可,功能完全一致:
中间件代码
public class AuthenticationMiddleware { private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { Debug.WriteLine("Process request"); // 调用后续管道中的中间件 await _next(context); Debug.WriteLine("Process response"); } }
注册中间件
在Startup.cs的Configure方法中添加注册,注意按你的业务需要调整中间件的注册顺序:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 其他原有中间件(比如异常处理、静态文件等) app.UseMiddleware<AuthenticationMiddleware>(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
内容的提问来源于stack exchange,提问作者Valey
相关产品推荐
相关产品推荐

