为控制器使用不同的路由模板

Rob*_*ert 2 c# asp.net-core-mvc asp.net-core-routing

是否可以在MVC中更改路由控制器名称?在MVC 5中,我会这样做:

[RoutePrefix("MySpecialSauce")]
public class ProductsController : Controller
{
    [Route("GetBy/{id}")]
    public MyObject GetBy(int id)
    {
        return something(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我所能找到的就是使用控制器的默认名称:

[Route("[controller]")]
public class ProductsController : Controller
{

    [HttpGet("GetBy/{id}")]
    public MyObject GetBy(int id)
    {
        return something(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想为我的路线使用与实际控制器名称不同的名称.你怎么做到这一点?

Nko*_*osi 6

您可以在Core中执行相同的操作

[Route("MySpecialSauce")]
public class ProductsController : Controller {

    [HttpGet("GetBy/{id:int}")]//Matches GET MySpecialSauce/GetBy/5
    public MyObject GetBy(int id) {
        return something(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

[controller]是帮助路由模板的令牌替代品.这不是强制性的.

路径模板中的源代码替换([controller],[action],[area])

为方便起见,属性路由通过将标记括在方括号([,])中来支持标记替换.标记[action], [area][controller]将被定义路径的操作中的操作名称,区域名称和控制器名称的值替换.