属性路由继承 [英] Attribute Routing Inheritance

查看:67
本文介绍了属性路由继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我一直在MVC应用程序中使用过这种方法

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()用于索引操作已返回/admin/products/list/

现在,在.NET Core中,它忽略了基类路由属性,结果仅为/products/list/ 这是.NET Core的新功能吗?有什么设置可以使系统结合 action + controller + base-controller 路由吗?

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?

推荐答案

我找不到自动组合 action + controller + base-controller 的方法,但是这样可以实现您想要的东西:

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()
    {
        ...
    }
}

此方法最终生成URL /admin/products/list,明显的缺点是products是每个操作都需要重复的内容.这可能是一个可以接受的折衷方案.由您决定.您可以使用常量使它更好地成为 bit ,例如:

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()
{
    ...
}

这不是很好,因为它只是一种解决方法,但是如果您不想使用 Chris Pratt的Areas建议.

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.

这篇关于属性路由继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆