Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

c# - Inject asp.net core middleware from inside a library to a specific location

I am developing a plugin and I need to inject another middleware into the user StartUp.cs, is there a way to it without modifying the user StartUp.cs?

The only way I can think of is actually patching the runtime and inject the required IL instructions to the start of UseXaf middleware that call my middleware first. However I am hoping there is build-in mechanism to it.

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();
question from:https://stackoverflow.com/questions/65851375/inject-asp-net-core-middleware-from-inside-a-library-to-a-specific-location

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create your own custom Middleware class. This can either be by implementing the IMiddleware interface or just creating a class with a public method named Invoke or InvokeAsync. To add the middleware to your pipeline you can create a static method like so:

public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
{
    return builder.UseMiddleware<CustomMiddleware>();
}

then in Startup.cs:

app.UseCustomMiddleware();

See this page for more information on middleware.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...