【问题标题】:Use different route template for controller为控制器使用不同的路由模板
【发布时间】:2017-04-03 15:27:16
【问题描述】:

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

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

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

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

    [HttpGet("GetBy/{id}")]
    public MyObject GetBy(int id)
    {
        return something(id);
    }
}

我想为我的路由使用与实际控制器名称不同的名称。你是怎么做到的?

【问题讨论】:

    标签: c# asp.net-core-mvc asp.net-core-routing


    【解决方案1】:

    你可以在 Core 中做同样的事情

    [Route("MySpecialSauce")]
    public class ProductsController : Controller {
    
        [HttpGet("GetBy/{id:int}")]//Matches GET MySpecialSauce/GetBy/5
        public MyObject GetBy(int id) {
            return something(id);
        }
    }
    

    [controller] 是用于帮助路由模板的令牌替换。这不是强制性的。

    来源Token replacement in route templates ([controller], [action], [area])

    为方便起见,属性路由支持令牌替换 将令牌括在方括号中([])。代币[action][area][controller] 将替换为 动作名称、区域名称和控制器名称。 路线已定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 2018-03-27
      • 2011-03-10
      相关资源
      最近更新 更多