ASP.NET Core Webアプリケーションのミドルウェアをクラスで実装する - ASP.NET Core

ASP.NET Core Webアプリケーションのミドルウェアをクラスで実装するコードを紹介します。

概要

こちらの記事では、Useメソッドを利用してミドルウェアを実行するコードを紹介しました。 Useメソッドには実行する処理のデリゲートを与えましたが、処理が複雑になりコードが多くなった場合、デリゲートではなくクラスとしてミドルウェアを実装したい場合があります。 この記事ではASP.NET Core Webアプリケーションのミドルウェアをクラスで実装するコードを紹介します。

プログラム例

コード

下記のコードを記述します。
MyMiddleWare1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace MiddlewareClass
{
  public class MyMiddleWare1
  {
    private readonly RequestDelegate _next;

    public MyMiddleWare1(RequestDelegate next)
    {
      _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
      await context.Response.WriteAsync("Hello ASP.NET Core World!!");
      await _next(context);
    }
  }
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MiddlewareClass
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseMiddleware<MyMiddleWare1>();
    }
  }
}

解説

MyMiddleWare1.cs でミドルウェアの実装をします。ミドルウェアの実行処理は InvokeAsync() メソッド、または Invoke() メソッドに実装します。今回のコードでは、"Hello ASP.NET Core World!!" をレスポンスとして返す処理を実装しています。
Startup.cs では app.UseMiddleware<(ミドルウェアのクラス名)>(); のコードを記述することでクラスで実装したミドルウェアを呼び出します。

実行結果

プロジェクトを実行します。下図の画面が表示されます。実装したミドルウェアのクラスの処理が実行できていることが確認できます。


プログラム例 : ミドルウェア拡張メソッドを利用する例

コード

下記のコードを記述します。
MyMiddleWare2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;

namespace MiddlewareClass
{
  public static class MyMiddleWare2Extensions
  {
    public static IApplicationBuilder UseMyMiddleWare2(this IApplicationBuilder app)
    {
      app.UseMiddleware<MyMiddleWare2>();

      return app;
    }
  }

  public class MyMiddleWare2
  {
    private readonly RequestDelegate _next;

    public MyMiddleWare2(RequestDelegate next)
    {
      _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
      await context.Response.WriteAsync("Hello ASP.NET Core World!! (Middleware Extension)");
      await _next(context);
    }
  }
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MiddlewareClass
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }
      app.UseMyMiddleWare2();
    }
  }
}

解説

MyMiddleWare2.cs でミドルウェアの実装をします。ミドルウェアの実行処理は InvokeAsync() メソッド、または Invoke() メソッドに実装します。今回のコードでは、"Hello ASP.NET Core World!! (Middleware Extension)" をレスポンスとして返す処理を実装しています。
Startup.cs では app.UseMyMiddleWare2(); のコードを記述し、ミドルウェア拡張メソッドを呼び出すことでクラスで実装したミドルウェアを呼び出します。

実行結果

プロジェクトを実行します。下図の画面が表示されます。実装したミドルウェアのクラスの処理が実行できていることが確認できます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-07
作成日: 2019-10-22
iPentec all rights reserverd.