Kareem Youssef
Kareem Youssef

Reputation: 89

Endpoints.MapControllerRoute pattern meaning

What is the use of assigning controller name and action name in the pattern like this

endpoints.MapControllerRoute(
                name:"default",
                pattern: "{controller=home}/{action=index}/{id?}"
                );

Upvotes: 3

Views: 2596

Answers (1)

abdusco
abdusco

Reputation: 11131

A pattern like

"{controller=home}/{action=index}/{id?}"

tells ASP.NET Core that if a URL ends with a path /MyController/MyAction/MyId123, it should dispatch the request to the method MyAction inside the controller MyController. That method could look like:

public class MyController {
    public IActionResult MyAction(string id) {
        // ...
    }
}

Now, by adding =home and =index, you give it a default value, and effectively matching all requests that don't map to an existing controller & action to HomeController:Index method.

From the docs:

The route template "{controller=Home}/{action=Index}/{id?}":

  • Matches a URL path like /Products/Details/5

  • Extracts the route values { controller = Products, action = Details, id = 5 } by tokenizing the path. The extraction of route values results in a match if the app has a controller named ProductsController and a Details action:

    public class ProductsController : Controller {
        public IActionResult Details(int id)
        {
            return ControllerContext.MyDisplayRouteInfo(id);
        } 
    } 
    
  • {controller=Home} defines Home as the default controller.

  • {action=Index} defines Index as the default action.

  • The ? character in {id?} defines id as optional.

Upvotes: 3

Related Questions