Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of registered middleware in ASP.NET Core?

In ASP.NET Core, you can register new middleware into the request processing pipeline during the Configure method of the startup class you're using for your web host builder by using app.UseMiddleware(...). During debugging, how do I get a list of registered middleware providers, though? I can't see any way to actually view the middleware that's been registered for the app.

like image 916
Jez Avatar asked Aug 20 '19 11:08

Jez


2 Answers

From another question that someone's pointed out is very similar to this one:

The list of middleware is not publically available, for some reason. In debug mode, though, it is available by examining the IApplicationBuilder app variable during execution of the Configure method, specifically the _components non-public member. This non-public member is an IList<Func<RequestDelegate, RequestDelegate>>, containing a list of entries representing the middlewares that have been registered so far.

like image 156
Jez Avatar answered Nov 20 '22 08:11

Jez


Though question is to get middleware list during debugging, just in case someone needs, following reflection based code can be used to get list of registered middleware in request pipeline programmatically:

private void CollectListOfMiddleware(IApplicationBuilder app)
{
    _listOfMiddleware = new StringBuilder();
    FieldInfo _componentsField = app.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Single(pi => pi.Name == "_components");
    List<Func<RequestDelegate, RequestDelegate>> _componentsValue =
        _componentsField.GetValue(app) as List<Func<RequestDelegate, RequestDelegate>>;
    _componentsValue.ForEach(x =>
    {
        FieldInfo middlewareField = x.Target.GetType().GetRuntimeFields().Single(pi => pi.Name == "middleware");
        object middlewareValue = middlewareField.GetValue(x.Target);
        _listOfMiddleware.Append($"{middlewareValue.ToString()}\n");
    }
    );
}
like image 42
shifatullah Avatar answered Nov 20 '22 10:11

shifatullah