为特定操作创建不同的路径

Creating a different route to a specific action

我正在开发 asp.net 5 mvc api,我目前正在开发 Accounts Controller。

因为我在许多不同的地方看到有使用 /api/Token 路由到 Web 登录 api 的约定。我想路由到没有帐户前缀的特定方法,我不想使用不同的控制器,我更喜欢在 Startup.cs 中使用属性而不是路由以避免将来混淆。

这是我目前拥有的

[Route("api/[controller]")]
public class AccountsController : Controller
{
    [HttpPost("login")]
    public async Task<JwtToken> Token([FromBody]Credentials credentials)
    {
     ...
    }

    [HttpPost]
    public async Task CreateUser([FromBody] userDto)
    {
      ...
    }
}

使用属性路由,您可以在 Action 的路由属性上使用 波浪号 (~) 来覆盖 Controller 的默认路由,如果需要:

[Route("api/[controller]")]
public class AccountsController : Controller {

    [HttpPost]
    [Route("~/api/token")] //routes to `/api/token`
    public async Task<JwtToken> Token([FromBody]Credentials credentials) {
        ...
    }

    [HttpPost] 
    [Route("users")] // routes to `/api/accounts/users`
    public async Task CreateUser([FromBody] userDto) {
        ...
    }
}

对于 ASP.NET 核心,似乎不再需要波浪号 ~ 符号(参见已接受的答案)来覆盖控制器的路由前缀 – 相反,the following rule 适用:

Route templates applied to an action that begin with a / don't get combined with route templates applied to the controller. This example matches a set of URL paths similar to the default route.

这是一个例子:

[Route("foo")]
public class FooController : Controller
{
    [Route("bar")] // combined with "foo" to map to route "/foo/bar"
    public IActionResult Bar()
    {
        // ...
    }

    [Route("/hello/world")] // not combined; maps to route "/hello/world"
    public IActionResult HelloWorld()
    {

    }   
}