在ASP.NET Core Web API中注册新的DelegatingHandler [英] Registering a new DelegatingHandler in ASP.NET Core Web API

查看:531
本文介绍了在ASP.NET Core Web API中注册新的DelegatingHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个扩展了DelegatingHandler的新Handler,使我能够在到达控制器之前做一些事情.我已经读过很多地方需要从DelegatingHandler继承,然后像这样覆盖OverSendAsync()的地方:

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);
    }
}

这一切都很好,很花花公子,除了它什么都不做,因为我没有在任何地方注册它!再次,我在很多地方看到我应该在WebApiConfig.cs中这样做,但这不是Web API的ASP.NET Core 版本的一部分.我试图在Startup.cs文件中的各种东西(Configure(),ConfigureServices()等)之间找到类似物,但是没有运气.

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

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

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.");
        }
    }
}

中间件可以利用UseMiddleware<T>扩展来 将服务直接注入其构造函数中,如 下面的例子.依赖注入服务会自动填充, 并且扩展名采用一个params参数数组,用于 非注入参数.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆