Table of Contents
When you are setting up an ASP.NET Core pipeline, order matters more than most developers realize. A common question I get from engineers new to minimal APIs is this: should you call UseRouting()
before MapGet()
or the other way around?
The short answer is: UseRouting()
must come before your endpoint mappings such as MapGet()
, MapPost()
, or controller registrations. Let’s look at why this matters.
What UseRouting()
Actually Does
UseRouting()
is the middleware that matches the incoming HTTP request to the correct endpoint based on the routing table. Without it, ASP.NET Core has no idea which endpoint is supposed to handle the request.
If you place your MapGet()
or MapControllers()
calls before UseRouting()
, the runtime will not be able to properly connect routes to handlers. You will usually end up with a 404, even though you wrote the route correctly.
A Broken Example
Consider this snippet:
var app = builder.Build();
app.MapGet("/hello", () => "Hello World");
app.UseRouting();
app.Run();
At first glance, it looks fine. But when you hit /hello
in the browser, you get a 404. Why? Because the routing middleware was added after the endpoint was already registered. The endpoint metadata never reached the part of the pipeline responsible for matching requests.
The Correct Order
Here is the right way:
var app = builder.Build();
app.UseRouting();
app.MapGet("/hello", () => "Hello World");
app.Run();
In this version, UseRouting()
is invoked early enough to prepare the routing table. The endpoint handler then plugs into that pipeline correctly, and /hello
responds as expected.
Personal Take
I often see junior developers shuffle middleware around until the app “just works.” While that may solve the immediate problem, it usually means they do not yet understand how the pipeline flows.
Expert tip: When in doubt, remember this order:
- Routing setup (
UseRouting
)- Middleware that acts on routes (auth, CORS, etc.)
- Endpoint registrations (
MapGet
,MapControllers
, etc.)
This pattern is not just convention. It ensures your middleware runs in the correct order and keeps the application predictable.
Closing Thoughts
So, should you use UseRouting()
or MapGet()
first? Always place UseRouting()
before your endpoint mappings. That single decision prevents mysterious 404s and ensures your middleware pipeline behaves as intended.
The pipeline in ASP.NET Core is powerful, but only if you respect the order. Once you understand why the order matters, you will spend less time chasing down confusing routing bugs and more time building features that matter.
Frequently Asked Questions
Do I need UseRouting in minimal APIs?
What happens if I call MapGet before UseRouting?
Does order matter for UseEndpoints too?
Can middleware run before routing is applied?
References
- Routing in ASP.NET Core | Microsoft Learn
- Minimal APIs quick reference | Microsoft Learn
- What are the differences between
app.UseRouting()
andapp.UseEndpoints()
- Stack Overflow