Creating a different route to a specific action mvc 6

南楼画角 提交于 2019-12-23 12:27:58

问题


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

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.

this is what I have currently

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

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

回答1:


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



回答2:


For ASP.NET Core it seems that the tilde ~ symbol (see accepted answer) is not needed anymore to override the controller's route prefix – instead, the following rule applies:

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.

Here is an example:

[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()
    {

    }   
}


来源:https://stackoverflow.com/questions/34709085/creating-a-different-route-to-a-specific-action-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!