In ASP.NET Core, is there a way to install middleware from Program.cs?

I am creating a support library for ASP.NET Core websites. I have a few middlewares that you need to enable, and they need to be added before any other middlewares because of what they do.

I can create an extension method on IWebHostBuilder to add services, also to configure logging, but I see no way to add middleware programmatically. Is there any way to do this? Looking at the source for WebHost / WebHostBuilder, nothing came of it.


Given the first comment, I may not have been clear enough. I know how to create middleware and use it. What I'm trying to do is make sure that when the Configure (IApplicationBuilder) method is called at startup using the framework, my middleware is already there. Similarly, you can run a ServiceConfiguration before starting, even when created. So an extension method like

public static IWebHostBuilder AddPayscaleHostingServices(this IWebHostBuilder webHostBuilder, string serviceName)
{
    return webHostBuilder.ConfigureServices(collection =>
    {
        collection.RegisterPayscaleHostingServices();
    }).ConfigureLogging(factory =>
    {

    });
}

gives me the opportunity to do some customization before the webHostBuilder.Build method, but I don't see anything like this for middleware / all on IApplicationBuilder.

Thanks Erick

+4
source share
1 answer

. , DI.

:

public class MyStartupFilter : IStartupFilter
{
    public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
    {
        return app =>
        {
            // Configure middleware
            // ...

            // Call the next configure method
            next(app);
        };
    }
}

next(app) .

IStartupFilter ConfigureServices:

services.AddSingleton<IStartupFilter, MyStartupFilter>();
+3

Source: https://habr.com/ru/post/1675588/


All Articles