Search code examples
c#asp.net-core

Difference between `MapControllerRoute`, `MapDefaultControllerRoute`, and `MapControllers`?


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.


Solution

  • 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.