使用 IMiddleware 时添加自定义中间件不起作用

Dra*_*ica 12 .net c# .net-core asp.net-core asp.net-core-middleware

我正在尝试向管道添加自定义中间件(为了更容易,我将选择 .NET Core 文档示例)。假设我们希望在调用 API 时设置西班牙文化。这是完美运行的代码:

public class RequestCultureMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        CultureInfo.CurrentCulture = new CultureInfo("es-ES");
        CultureInfo.CurrentUICulture = new CultureInfo("es-ES");

        // Call the next delegate/middleware in the pipeline
        await _next(context);
    }
}

public static class RequestCultureMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestCulture(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestCultureMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

和启动类:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

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

        //here is our custom middleware!
        app.UseRequestCulture();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这很好,但是正如您所看到的,RequestCultureMiddleware 没有实现接口或基类/抽象类。您只需要记住在定义中间件以创建接收下一个中间件的构造函数时,您还需要创建一个专门名为“InvokeAsync”的方法,并将“HttpContext”作为参数。

我试图找到一个合同......一个基类或一个接口,猜猜是什么,我们有“IMiddleware”,它是“Microsoft.AspNetCore.Http”程序集的一部分。哇,这太完美了。让我们实施它。

界面如下所示:

namespace Microsoft.AspNetCore.Http
{
    //
    // Summary:
    //     Defines middleware that can be added to the application's request pipeline.
    public interface IMiddleware
    {
        //
        // Summary:
        //     Request handling method.
        //
        // Parameters:
        //   context:
        //     The Microsoft.AspNetCore.Http.HttpContext for the current request.
        //
        //   next:
        //     The delegate representing the remaining middleware in the request pipeline.
        //
        // Returns:
        //     A System.Threading.Tasks.Task that represents the execution of this middleware.
        Task InvokeAsync(HttpContext context, RequestDelegate next);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是实现:

    public class RequestCultureMiddleware : IMiddleware
    {

        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            CultureInfo.CurrentCulture = new CultureInfo("es-ES");
            CultureInfo.CurrentUICulture = new CultureInfo("es-ES");

            // Call the next delegate/middleware in the pipeline
            return next(context);
        }
    }


    public static class RequestCultureMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestCulture(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestCultureMiddleware>();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在运行 API 时,我在运行时收到以下错误:

System.InvalidOperationException: No service for type 'WebApplication1.RequestCultureMiddleware' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.AspNetCore.Http.MiddlewareFactory.Create(Type middlewareType)
   at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass5_1.<<UseMiddlewareInterface>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Run Code Online (Sandbox Code Playgroud)

如果不使用扩展名“UseMiddleware”,我应该如何注册这个中间件?谢谢。

小智 19

我确信这个问题在 5 个月后早就解决了,但我写这个建议是为了以防万一。

问题是即使您在启动的“配置”方法中内置了自定义中间件程序的“InvokeAsync”方法,也不会执行它。

前几天我遇到了同样的问题并解决了它,但我在 app.UseEndpoints 方法之前放置了内置代码。

在你的情况下

app.UseAuthorization();
app.UseRequestCulture();  // <- this way.
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你把它放在app.UseEndpoints方法之后,构造函数会被调用,但是InvokeAsync方法不会被执行。

  • 正如所解释的那样,这对我来说完全有效。读者应该遵循这两个答案 (3认同)
  • 这对我有用。我没有实现任何接口。我只是将中间件移到 `UseEndpoints` 之上,它就开始工作了。 (2认同)

Kir*_*kin 9

您正在使用基于工厂的中间件。如这些文档中所述,您错过了一个重要步骤:

...容器中注册的IMiddlewareFactory实例用于解析IMiddleware实现,而不是使用基于约定的中间件激活逻辑。中间件在应用程序的服务容器中注册为作用域或临时服务

在您的情况下,该注册将如下所示:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddTransient<RequestCultureMiddleware>();
}
Run Code Online (Sandbox Code Playgroud)