本文介绍了为特定操作创建不同的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on an asp.net 5 mvc api, and I am currently working on the Accounts Controller.

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

since I saw in many different places that there is a convention of using /api/Tokenrouting to a login in a web api. I would like to route to that specific method without the accounts prefix, I would prefer not using a different controller, and I would prefer using Attributes over routing in Startup.cs to avoid confusion in the future.

这是我目前拥有的

[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 的默认路由:

With attribute routing you can use a tilde (~) on the Action's route attribute to override the default route of the Controller if needed:

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

这篇关于为特定操作创建不同的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:48