I'm upgrading .NET Core 2.1 to .NET Core 3.0 and I saw here I have to use UseEndpoints
. However, at some pages I've seen it with either MapControllerRoute
, MapDefaultControllerRoute
, or MapControllers
.
I checked at the documentation and I saw that MapDefaultControllerRoute
is basically the same as MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}")
. But I don't understand the difference with MapControllers
. What does this last function actually do? The documentation says: "Adds endpoints for controller actions to the IEndpointRouteBuilder without specifying any routes.", but I don't get it, sorry.
MapDefaultControllerRoute This is the above, but it shorthands the configuration of the default pattern that I displayed above. 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.
In short, Convention Routing approaches Routing from the general case; you generally add some routes that will match all or most of your URLs, then add more specific routes for more specialized cases. The other way to approach this problem is via Attribute Routing.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still fully supported.
MapControllerRoute
Uses conventional routing (most often used in an MVC application), and sets up the URL route pattern. So you will have seen this in tutorials/documentation with something like this:
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
You could set this to whatever you wanted (within reason) and your routes would follow this pattern. The above pattern is basically {{root_url}}/{{name_of_controller}}/{{name_of_action}}/{{optional_id}}
where, if controller and action are not supplied, it defaults to home/index
.
MapDefaultControllerRoute This is the above, but it shorthands the configuration of the default pattern that I displayed above.
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.
N.B. It's entirely possible to use MapControllerRoute (and by proxy MapDefaultControllerRoute) along side attribute routing as well. If the user does not supply attributes, it will use the defined default pattern.
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