Reputation: 1330
I always used this approach in my MVC applications before
[Route("admin")]
public class AdminController : Controller
{
}
[Route("products")]
public class ProductsAdminController :AdminController
{
[Route("list")]
public IActionResult Index()
{
...
}
}
Url.RouteUrl() for Index action returned /admin/products/list/
Now in .NET Core it ignores base class route attribute and result is just /products/list/ Is this new to .NET Core? Is there any setup so system can combine action + controller + base-controller routes?
Upvotes: 12
Views: 6963
Reputation: 497
Anyone still looking for a way to define "baseURL/ControllerName" in .Net core 3.1. You would need to define RouteAttribute on your base controller like this:
[Route("admin/[controller]")]
Note [controller]
would allow the routing to automatically take the controller name in child class.
Upvotes: -2
Reputation: 93113
I can't find a way to combine action + controller + base-controller automatically, but it is possible to achieve what you're looking for like this:
[Route("admin")]
public class AdminController : Controller { }
public class ProductsAdminController : AdminController
{
[Route("products/list")]
public IActionResult Index()
{
...
}
}
This approach ends up generating a URL of /admin/products/list
, with the obvious downside that products
is something that needs to be repeated for each action. This might be an acceptable compromise; that's up to you to decide. You could make it a bit better with a constant, like this:
private const string RoutePrefix = "products";
[Route(RoutePrefix + "/list")]
public IActionResult Index()
{
...
}
It's not pretty as it's just a workaround, but worth considering if you don't want to go with Chris Pratt's Areas suggestion.
Upvotes: 5
Reputation: 239300
As far as I'm aware, that never would have worked. You could use areas, and by applying the [Area]
attribute to the base controller, you'd get the result you describe:
[Area("admin")]
public class AdminController : Controller
[Route("products")]
public class ProductsAdminController : AdminController
The same would work in Core, as well.
Upvotes: 3