gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:26:52 26 4
gpt4 key购买 nike

我正在尝试向管道添加自定义中间件(为了更容易,我将选择 .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>();
}
}

和 Startup 类:

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

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

我试图找到一个契约...一个基类或一个接口(interface),你猜怎么着,我们有“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);
}
}

这是实现:

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

但是,在运行 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)

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

最佳答案

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

问题是,即使您在 Startup 的“Configure”方法中内置了自定义中间件程序的“InvokeAsync”方法,该方法也不会被执行。

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

就你的情况

app.UseAuthorization();
app.UseRequestCulture(); // <- this way.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

顺便说一下,如果放在app.UseEndpoints方法后面,构造函数会被调用,但InvokeAsync方法不会被执行。

关于c# - 使用 IMiddleware 时添加自定义中间件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com