ASP.NET Core MVC Attribute Routing Inheritance

*爱你&永不变心* 提交于 2019-12-10 13:24:38

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/52335344/asp-net-core-mvc-attribute-routing-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!