きなこもち.net

.NET Framework × UiPath,Orchestrator × Azure × AWS × Angularなどの忘備録

手探り入門×ASP.net core ×Middle wareの開発と実行

この記事の目的

ASP.net coreでCustom Middle wareを導入するために必要な情報をまとめること。
Markdown記法になれること。※今回から、Markdownを使い始めました(∩´∀`)∩ワーイ

本題

Middle wareの概要

docs.microsoft.com

Middle wareクラスの作成

以下のクラスを作成します。

    public class MyCustomMiddleware1
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public MyCustomMiddleware1(RequestDelegate next, ILoggerFactory logFactory)
        {
            _next = next;
            _logger = logFactory.CreateLogger(typeof(MyCustomMiddleware1));
        }

        public async Task Invoke(HttpContext httpContext)
        {
            _logger.LogInformation($"Request Method = {httpContext.Request.Method}");
            _logger.LogInformation($"Request Path = {httpContext.Request.Path}");
            _logger.LogInformation($"Request User = {httpContext.User.Identity.Name}");
            //次のミドルウェア呼び出し
            await _next(httpContext);
            _logger.LogInformation($"Process End");
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class MyCustomMiddleware1Extensions
    {
        public static IApplicationBuilder UseMyCustomMiddleware1(this IApplicationBuilder app)
        {
            return app.UseMiddleware<MyCustomMiddleware1>();
        }
    }

Middle wareの導入

公式ドキュメントによると・・・

Startup.Configure メソッドでミドルウェア コンポーネントを追加する順序は、要求でミドルウェア コンポーネントが呼び出される順序および応答での逆の順序を定義します。 この順序は、セキュリティ、パフォーマンス、および機能にとって重要です。
The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

とのこと。実際には、順序を意識して設定する必要がありますが、今回は、Swagger(あらかじめ設定してあったもの)の後ろに追加することにします。 ※ここで、Swaggerの前に登録すると、/swagger のリクエストにも、/weatherforecast(テンプレートで用意されていたAPI)のリクエストにも反応します。デバッグ時に厄介なのと、Swaggerに対してミドルウェアが操作するようなこともないので、今回は後ろに設定しています。

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
            });
            app.UseMyCustomMiddleware1(); //HERE
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

参考) docs.microsoft.com

動作確認

/weatherforecast呼び出し後

/swagger呼び出し後
- ブレイクポイントに引っかからず処理終了

まとめ

ASP.NET の時にPreRequestHandlerExecuteとか、PostRequestHandlerExecuteに組み込んでいた処理を、ASP.NET Core では、ミドルウェアを活用して実現できることが何となくわかった( ゚Д゚)。その際、処理のパイプラインは、Start UpクラスのConfigurateメソッドで設定するミドルウェアの登録順序が大事であるらしい。 Pre/Post Request Handlerの次に気になるのは、集約エラー処理・・・次は、それを調べてみよう。

docs.microsoft.com

docs.microsoft.com