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

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

问题描述

我正在开发一个 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) {
        ...
    }
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)