在 ASP.NET Core Web API 中注册一个新的 DelegatingHandler

编程入门 行业动态 更新时间:2024-10-19 00:21:45
本文介绍了在 ASP.NET Core Web API 中注册一个新的 DelegatingHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想创建一个扩展 DelegatingHandler 的新处理程序,使我能够在到达控制器之前做一些事情.我在各个地方都读到过,我需要从 DelegatingHandler 继承然后像这样覆盖 SendAsync():

public class ApiKeyHandler : DelegatingHandler{受保护的覆盖任务SendAsync(HttpRequestMessage 请求,CancellationToken 取消令牌){//在这里做自定义的东西返回 base.SendAsync(请求,取消令牌);}}

这一切都很好,但它没有做任何事情,因为我没有在任何地方注册它!同样,我在很多地方都看到我应该在 WebApiConfig.cs 中这样做,但这不是 ASP.NET Core 版本的 Web API 的一部分.我试图在 Startup.cs 文件(Configure()、ConfigureServices() 等)中找到各种类似的东西,但没有找到.

谁能告诉我应该如何注册我的新处理程序?

解决方案

正如在之前的评论中已经提到的,查看 编写自己的中间件

您的 ApiKeyHandler 可以转换为一个中间件类,该类在其构造函数中接收下一个 RequestDelegate 并支持 Invoke 方法,如下所示:

使用 System.Threading.Tasks;使用 Microsoft.AspNetCore.Http;使用 Microsoft.Extensions.Logging;命名空间 MyMiddlewareNamespace {公共类 ApiKeyMiddleware {私有只读 RequestDelegate _next;私有只读 ILogger _logger;私人 IApiKeyService _service;public ApiKeyMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IApiKeyService service) {_next = 下一个;_logger = loggerFactory.CreateLogger();_service = 服务}公共异步任务调用(HttpContext 上下文){_logger.LogInformation("处理 API 密钥:" + context.Request.Path);//在这里用服务做自定义的东西等待_next.Invoke(上下文);_logger.LogInformation(已完成处理api密钥.");}}}

中间件可以利用 UseMiddleware 扩展将服务直接注入到它们的构造函数中,如下面的例子.依赖注入的服务自动填充,并且扩展需要一个 params 参数数组用于非注入参数.

ApiKeyExtensions.cs

public static class ApiKeyExtensions {公共静态 IApplicationBuilder UseApiKey(这个 IApplicationBuilder 构建器){返回 builder.UseMiddleware();}}

使用扩展方法和关联的中间件类,配置方法变得非常简单易读.

public void Configure(IApplicationBuilder app) {//...其他配置app.UseApiKey();//...其他配置}

I want to create a new Handler that extends DelegatingHandler to enable me to do stuff before getting as far as the controller. I have read in various places that I need need to inherit from DelegatingHandler then overrride SendAsync() like this:

public class ApiKeyHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // do custom stuff here return base.SendAsync(request, cancellationToken); } }

This is all fine and dandy except it doesn't do anything because I haven't registered it anywhere! Again, I have seen in numerous places that I should do so in WebApiConfig.cs but that is not a part of the ASP.NET Core version of Web API. I have tried to find analogues amoungst the various things in the Startup.cs file (Configure(), ConfigureServices() etc) but no luck.

Can anyone please tell me how I should go about registering my new handler?

解决方案

As already mentioned in previous comment, look into Writing your own middleware

Your ApiKeyHandler can be converted into a middleware class that takes in the next RequestDelegate in its constructor and supports an Invoke method as shown:

using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace MyMiddlewareNamespace { public class ApiKeyMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; private IApiKeyService _service; public ApiKeyMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IApiKeyService service) { _next = next; _logger = loggerFactory.CreateLogger<ApiKeyMiddleware>(); _service = service } public async Task Invoke(HttpContext context) { _logger.LogInformation("Handling API key for: " + context.Request.Path); // do custom stuff here with service await _next.Invoke(context); _logger.LogInformation("Finished handling api key."); } } }

Middleware can take advantage of the UseMiddleware<T> extension to inject services directly into their constructors, as shown in the example below. Dependency injected services are automatically filled, and the extension takes a params array of arguments to be used for non-injected parameters.

ApiKeyExtensions.cs

public static class ApiKeyExtensions { public static IApplicationBuilder UseApiKey(this IApplicationBuilder builder) { return builder.UseMiddleware<ApiKeyMiddleware>(); } }

Using the extension method and associated middleware class, the Configure method becomes very simple and readable.

public void Configure(IApplicationBuilder app) { //...other configuration app.UseApiKey(); //...other configuration }

更多推荐

在 ASP.NET Core Web API 中注册一个新的 DelegatingHandler

本文发布于:2023-11-14 04:20:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586199.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   NET   ASP   DelegatingHandler   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!