[译] ASP.NET MVC 6 attribute routing – the [controller] and [action] tokens

时间:2023-03-09 01:33:08
[译] ASP.NET MVC 6 attribute routing – the [controller] and [action] tokens

原文:http://www.strathweb.com/2015/01/asp-net-mvc-6-attribute-routing-controller-action-tokens/

当在Web API 2或者MVC 5 中使用路由属性很容易发生路由和控制器的名字不同步的情况. 这是因为路由通常就是一个字符串, 因此当改变了控制器的名字我们同时也要去修改路由属性.

当时我们通常会忘记修改.

在MVC 6中这个问题得到了改善 – 通过引入 [controller] 和 [action] tokens 到路由属性.

问题

一个典型Web API项目的控制器代码如下:

[Route("api/hello")]
public class HelloController : Controller
{
[Route]
public string Get()
{
return "hello";
}
}

或者:

[Route("api/hello")]
public class HelloController : Controller
{
[Route("GetHello")]
public string GetHello()
{
return "hello";
}
}

在上面的两个例子中 我们通常需要手工去维护Route属性.

MVC6的解决方案

通过使用新的 [controller] token你可以保证你的路由和控制器的名字保持一样. 在下面的例子中, [controller] 始终保持和控制器的名字一样 – 在这个例子中Route的名字是Hello.

[Route("api/[controller]")]
public class HelloController : Controller
{
[Route]
public string Get()
{
return "hello";
}
}

[action] token – 这个应用在aciton上 保持路由名和action的名字一致.

下面的例子中action匹配 /api/hello/GetHello/1 URL.

[Route("api/[controller]")]
public class HelloController : Controller
{
[Route("[action]/{id:int}")]
public string GetHello(int id)
{
return "hello " + id;
}
}