I am using Asp.net 6 web API in my project and I am confused about understanding routing functions. Previously when we build API we use to use following middleware
app.UseRouting()
...Other middleware
app.UseEndPoints()
But now in Asp.Net 6 the default way to use this
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers()
No need to use app.UseRouting() and app.UseEndPoints() rather use directly app.MapControllers() after other middlwares
I wonder what app.MapControllers() does internally? Does it mean that all routes are authorized by defualt?
How to use other middleware before registering routes? I am kind of confused to understand between these approaches
app.UseRouting() VS app.UseEndpoints() VS app.MapControllers();
You got couple sub-questions. Here is the list and my answer. Please comment if I miss any:
What app.MapControllers() does internally?
app.MapControllers() is a helper used to map attribute routing. The app itself is also an IEndpointRouteBuilder and this helper will add end points from your attribute-routed controllers. To map conventional routing use the app.MapControllerRoute().
Does it mean that all routes are authorized by default?
Adding app.UseAuthorization(); does not mean that the route is not
"authorized by default" but the pipeline will try to determine if current user can be authorized to access this route.
How to use other middleware before registering routes?
If you mean the UseAuthentication() and UseAuthorization(), they must be placed after the UseRouting() and before UseEndPoints(). You can check the middleware order for further info.
I am kind of confused to understand between these approaches
app.UseRouting() VS app.UseEndpoints() VS app.MapControllers();:
The UseRouting() and UseEndpoints() (also MapGet() and MapPost()) are used to manually craft a tailored routing to meet your need. The MapControllers(), as mentioned above, is a handy helper if you are using attribute routing with controllers in a typical Web API scenario.
UseRouting: Matches request to an endpoint.
UseEndpoints: Execute the matched endpoint.
MapControllers : This doesn't make any assumptions about routing and will rely on the user doing attribute routing (most commonly used in WebAPI controllers) to get requests to the right place.
This makes the ASP.NET Core framework more flexible and allows other middlewares to act between UseRouting and UseEndpoints. That allows those middlewares to utilize the information from endpoint routing, for example, the call to UseAuthentication must go after UseRouting, so that route information is available for authentication decisions and before UseEndpoints so that users are authenticated before accessing the endpoints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With