gpt4 book ai didi

c# - 将 asp.net 核心中间件从库内部注入(inject)到特定位置

转载 作者:行者123 更新时间:2023-12-04 08:13:06 25 4
gpt4 key购买 nike

我正在开发一个插件,我需要向用户 StartUp.cs 注入(inject)另一个中间件,有没有办法在不修改用户 StartUp.cs 的情况下实现它?
我能想到的唯一方法实际上是修补运行时并将所需的 IL 指令注入(inject) UseXaf 的开头首先调用我的中间件的中间件。但是我希望它有内置机制。

if(env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
else {
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();

//INJECT IT HERE <---------

app.UseXaf();

最佳答案

我的解决方案是实际修补运行时并注入(inject)指令以在 UseXaf 之前调用我的自定义中间件。中间件。
使用 https://github.com/pardeike/Harmony 可以轻松完成图书馆为:

    public class UseHangfire : IStartupFilter {
private static readonly Harmony Harmony=new Harmony(nameof(UseHangfire));
static UseHangfire() {
var methodInfo = typeof(StartupExtensions).Method(nameof(StartupExtensions.UseXaf),Flags.StaticPublic);
Harmony.Patch(methodInfo,postfix:new HarmonyMethod(typeof(UseHangfire),nameof(UseXaf))); //runtime patching of the UseXaf middleware
}

public static void UseXaf(IApplicationBuilder builder) => Dashboard?.Invoke(builder); //inject the Hangfire Dashboard and authorize before UseXaf is used

public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => next;

public static Action<IApplicationBuilder> Dashboard = builder
=> builder.UseHangfireDashboard(options:new DashboardOptions {Authorization = new[] {new DashboardAuthorization()}
});
}

public class DashboardAuthorization : IDashboardAuthorizationFilter {
public bool Authorize(DashboardContext context)
=> context.GetHttpContext().User.Identity.IsAuthenticated;
}

public class HangfireStartup : IHostingStartup{
public void Configure(IWebHostBuilder builder)
=> builder.ConfigureServices(services => services
.AddSingleton<IStartupFilter, UseHangfire>()
);
}

在剥离的片段中,您可以看到我如何使用 asp.net 核心 IHostingStartup在我的图书馆内注册 IStartupFilter而他又在运行时修补 UseXaf中间件(带有 OHarmony 库)调用 UseHangfireDashboard中间件在我需要的确切位置。
用 C# 打字更难用英文描述 :)
注意事项:根据实际要修补的内容,您应该知道编译器可能会针对不同的框架内联或不内联它。在他们的 wiki 上阅读更多信息 Inlining

关于c# - 将 asp.net 核心中间件从库内部注入(inject)到特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65851375/

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