简体   繁体   中英

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?

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM