c# - 如何为 {id}/visit 创建有效路线?

标签 c# asp.net-core asp.net-core-webapi asp.net-core-routing

我是 asp.core 的新手,所以我尝试创建到 {id}/visits

的有效路径

我的代码:

[Produces("application/json")]
[Route("/Users")]
public class UserController 
{
    [HttpGet]
    [Route("{id}/visits")]
    public async Task<IActionResult> GetUser([FromRoute] long id)
    {
        throw new NotImplementedException()
    }
}

但是,在路由 {id} 生成的方法相同:

// GET: /Users/5
[HttpGet("{id}")]
public async Task<IActionResult> GetUser([FromRoute] long id)
{
    return Ok(user);
}

如何创建路径/Users/5/visits nethod?
我应该在 GetUser 添加哪些参数?

最佳答案

以不同的方式命名方法并使用约束来避免路由冲突:

[Produces("application/json")]
[RoutePrefix("Users")] // different attribute here and not starting /slash
public class UserController 
{
    // Gets a specific user
    [HttpGet]
    [Route("{id:long}")] // Matches GET Users/5
    public async Task<IActionResult> GetUser([FromRoute] long id)
    {
        // do what needs to be done
    }

    // Gets all visits from a specific user
    [HttpGet]
    [Route("{id:long}/visits")] // Matches GET Users/5/visits
    public async Task<IActionResult> GetUserVisits([FromRoute] long id) // method name different
    {
        // do what needs to be done
    }
}

关于c# - 如何为 {id}/visit 创建有效路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680096/

相关文章:

c# - 有没有一种方法可以在不使用构造函数的情况下初始化结构的成员?

c# - .NET Core 中的自定义授权属性

C# AutoMapperMappingException KeyNotFoundException 异常

c# - 路线总是去第一个 maproute

asp.net-core - asp.net 核心 Controller 操作路由使用编码斜杠来确定路由(仅限 IIS)

c# - 生成 NSwag 客户端作为构建的一部分

c# - 如何在登录流程中查找客户端 ID

c# - 在 ASP.NET Core WebAPI 中获取 OData 计数

c# - 使用 .Net Core API 从 Azure Blob 存储异步流式传输视频

powerbi - 使用 MSAL 获取访问 token 并将其缓存在 SQL DB 中,而无需使用 MSAL 登录