在ASP.NET Core中,是否可以通过Program.cs设置中间件? [英] in ASP.NET Core, is there any way to set up middleware from Program.cs?
问题描述
我正在为ASP.NET Core网站构建一个支持库.我有一些中间件需要启用,并且由于其作用,需要在任何其他中间件之前添加它们.
I am building a support library for ASP.NET Core websites. I have a few pieces of middleware that need to be enabled, and they need to be added before any other middleware due what they do.
我可以在IWebHostBuilder上创建扩展方法来添加服务,同样用于配置日志记录,但是我看不到以编程方式添加中间件的任何方法.有什么办法吗?在查看WebHost/WebHostBuilder的源代码时,没有发现任何问题.
I can create an extension method on IWebHostBuilder to add services, likewise for configuring logging, but I don't see any way to add middleware in a programmatic way. Is there any way to do this? Looking at the source for WebHost/WebHostBuilder nothing jumped out.
鉴于第一个评论,我可能还不够清楚.我知道如何创建和使用中间件.我正在尝试做的是确保当框架在启动时调用Configure(IApplicationBuilder app)方法时,我的中间件已经到位.以类似于甚至可以在启动之前执行ServiceConfiguration的方式.像这样的扩展方法
Given the first comment, I may not have been clear enough. I know how to create middleware and use it. What I am trying to do is ensure that when the Configure(IApplicationBuilder app) method is called on Startup by the framework, my middleware is already in place. In a similar manner to being able to do ServiceConfiguration prior to Startup even being created. So an extension method like
public static IWebHostBuilder AddPayscaleHostingServices(this IWebHostBuilder webHostBuilder, string serviceName)
{
return webHostBuilder.ConfigureServices(collection =>
{
collection.RegisterPayscaleHostingServices();
}).ConfigureLogging(factory =>
{
});
}
使我能够在webHostBuilder.Build方法之前进行一些设置,但对于IApplicationBuilder上的中间件/任何东西,我看不到任何类似的东西.
gives me the ability to do some setup prior to the webHostBuilder.Build method, but I don't see anything similar for middleware/anything on IApplicationBuilder.
谢谢,埃里克
推荐答案
您可以使用启动过滤器来实现此目的.启动过滤器使您可以从DI容器解析的服务中配置中间件.
You could use a startup filter to achieve this. Startup filters allow you to configure middleware from a service resolved from the DI container.
定义启动过滤器很容易:
Defining a startup filter is easy:
public class MyStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
// Configure middleware
// ...
// Call the next configure method
next(app);
};
}
}
始终确保调用 next(app)
或不会配置任何其他中间件.
Always make sure to call next(app)
or any other middleware won't be configured.
现在在 ConfigureServices
方法中将启动过滤器注册为 IStartupFilter
的单例实现:
Now register the startup filter as a singleton implementation of IStartupFilter
in your ConfigureServices
method:
services.AddSingleton<IStartupFilter, MyStartupFilter>();
这篇关于在ASP.NET Core中,是否可以通过Program.cs设置中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!