mbudnik
mbudnik

Reputation: 2107

How to get a list of middlewares in ASP.NET Core

How do I get a list of active middlewares? How do I get a list of middlewares for specific url (each url may have a different set of middlewares added to the pipeline)?

I would like to know which middlewares are being added by using some of the common builder extensions like UseMvc() or app.UseIdentity();

I know I could check the source code of each extension. Is there a runtime method to get this?

Upvotes: 8

Views: 2362

Answers (3)

chick3n0x07CC
chick3n0x07CC

Reputation: 798

To add on another answer, in .NET 6.0, I got it with the debugger: in Program.cs put a breakpoint in app.Run(), which executes once the pipeline has been set (refer to all those app.UseMyMiddlewareName() statements). Then, inspect the app variable and follow this path:

app > Non-Public members > ApplicationBuilder > Non-Publi members > _components

There we have the list of middlewares. For each item in the list, follow:

[<itemIndex>] > Target > middleware

Just a curious note: as we now, the order in which we specifiy the middlewares in the code matters. If we change that order, the list in the debugger will reflect it accordingly.

enter image description here

Upvotes: 2

Oleg Lemeshenko
Oleg Lemeshenko

Reputation: 78

You can see a list of middlewares in Stack. You can add your middleware last, put a breakpoint somewhere in the Invoke method. When debugger will stop, you will see all previous calls to other middlewares.

Upvotes: 2

Henk Mollema
Henk Mollema

Reputation: 46621

No, you can't. When you add a middleware to the pipeline, it's resolved to a Func<RequestDelegate, RequestDelegate>. The components are saved in a private field in the ApplicationBuilder implementation. You could however bake an extension method with some reflection magic to determine the actual middleware type, but it's not trivial.

Upvotes: 6

Related Questions