2

I am trying to use Microsoft.AspNetCore.Routing with multiple widdlewares which can match. For example:

builder.MapRoute("api", async c => {}) // Match all api calls

builder.MapRoute("api/user", async c => {}) // Only api/user

builder.MapRoute("api/client", async c => {}) // Only api/client

But currently the only one of them can match.

If I will make MapRoute("api/{*postfix}", handler), then only this handler will run and api/client and api/user wouldn't.

Is there a way to handle multiple matches?

Tseng
  • 61,549
  • 15
  • 193
  • 205

1 Answers1

4

Try registering a common middleware first, e.g. by using .MapWhen(...) and inside that middleware put your .MapRoute(..) child middlewares. The order in which you register your middlewares does matter and also you need to understand how "branching" works:

https://docs.asp.net/en/latest/fundamentals/middleware.html

In addition to path-based mapping, the MapWhen method supports predicate-based middleware branching, allowing separate pipelines to be constructed in a very flexible fashion. Any predicate of type Func can be used to map requests to a new branch of the pipeline.

Check out this video that explains the concept:

The basics of middleware in ASP.NET Core

Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121