12

DelegatingHandlerを拡張して、コントローラまで移動する前に処理できるようにする新しいHandlerを作成したいと思います。ASP.NET Core Web APIで新しいDelegatingHandlerを登録する

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

     return base.SendAsync(request, cancellationToken); 
    } 
} 

これは私がどこにも登録していないので、それは何もしない以外のすべての罰金とダンディです:私は、私は、このようなSendAsync()書き換えてDelegatingHandlerから継承する必要がある必要がある様々な場所で読んだことがあります!繰り返しますが、私はWebApiConfig.csでこれを行うべきであることを多くの場所で見てきましたが、それはASP.NET コアバージョンのWeb APIの一部ではありません。私は、Startup.csファイル(Configure()、ConfigureServices()など)のさまざまなものの中でアナログを見つけることを試みましたが、運はありません。

誰でも私の新しいハンドラの登録方法について教えてください。すでに以前のコメントで述べた

+1

彼らが今なくなっている、たとえば[この記事](http://www.dotnetcurry.com/aspnet-mvc/1149/convert-aspnet-webapi2-aspnet5-mvc6)を参照してください。代わりにOWINミドルウェアを書くことをお勧めします。 – Andrei

+0

前のコメントですでに述べたように、[ミドルウェアの作成](https://docs.asp.net/ja/latest/fundamentals/middleware.html#writing-middleware)を参照してください。 – Nkosi

答えて

13

としては、Writing your own middleware

に見てあなたのApiKeyHandlerは、コンストラクタで次のRequestDelegateを取り込んで示すようInvoke方法をサポートするミドルウェアクラスに変換することができます。

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

ミドルウェアは、に示すように、の拡張子を利用して、コンストラクタにサービスを直接注入できます。以下の例。依存関係注入サービスは、 に自動的に入力され、拡張子は、 非注入パラメータに使用される引数配列のparamsの配列をとります。

ApiKeyExtensions.cs拡張メソッドおよび関連するミドルウェアクラスを使用して

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

、 設定方法は非常にシンプルで読みやすいとなります。

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

    app.UseApiKey(); 

    //...other configuration 
} 
関連する問題