Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute Routing Inheritance

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?

like image 579
Michael Samteladze Avatar asked Sep 14 '18 15:09

Michael Samteladze


2 Answers

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.

like image 100
Kirk Larkin Avatar answered Sep 22 '22 22:09

Kirk Larkin


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.

like image 27
Chris Pratt Avatar answered Sep 20 '22 22:09

Chris Pratt