创建到特定动作MVC 6的不同路径 [英] Creating a different route to a specific action mvc 6
问题描述
我正在使用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
routing到Web api中的登录名的约定.我想路由到不带帐户前缀的特定方法,我希望不使用其他控制器,并且更喜欢在Startup.cs中使用属性"而不是路由,以避免将来造成混淆.
since I saw in many different places that there is a convention of using /api/Token
routing 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
的route属性上使用波浪号(〜)来覆盖默认路由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) {
...
}
}
这篇关于创建到特定动作MVC 6的不同路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!