In Program.cs
how do I write app.MapControllerRoute
to take /
to my HomeController.cs public IActionResult Index()
and /CategoryNameHere
to my CategoryController.cs public IActionResult Index(string category)
?
I've got the out of the box routing in my Program.cs
:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "category",
pattern: "WhatGoesHere?",
defaults: new { controller = "Category", action = "Index" });
Just define the pattern as "{category}"
:
app.MapControllerRoute(
name: "category",
pattern: "{category}",
defaults: new { controller = "Category", action = "Index" });
The category
in the pattern here is match to the parameter name in the public IActionResult Index(string category)
action method of the Category
controller.
By the way, the same result you can achieve by using the Route
attribute instead of the conventional routing:
[Route("{category}")]
public IActionResult Index(string category)
{
return View((object)category);
}
For an additional information see: Routing to controller actions in ASP.NET Core