处理 ID 为字符串和整数的 WebApi 核心方法

Handle WebApi Core methods with Id as string and int

我有两个方法:

    [HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }

如您所见,我想传递给我的 API 路由,例如:

https://localhost:44365/Task/1

https://localhost:44365/Task/string

但是我的WebApi项目无法处理它。当我通过这样的路线时:

https://localhost:44365/Task/7dd2514618c4-4575b3b6f2e9731edd61

我收到一个 400 http 和这个回复:

{
"id": [
    "The value '7dd2514618c4-4575b3b6f2e9731edd61' is not valid."
]
}

调试时,我没有遇到任何方法(当我传递字符串而不是 int 时)

我的问题是,如何使用 stringint 的一个参数来验证方法?这些方法做不同的事情

编辑

当我通过类似的东西时:

https://localhost:44365/Task/dddd

我仍然收到无效的回复 id

像这样使用

[HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("User/{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }

并在使用 guid/string 调用 api 时使用

https://localhost:44365/Task/User/7dd2514618c4-4575b3b6f2e9731edd61

您可以像[HttpGet("{id:int}")]一样定义参数类型。有关详细信息,请参阅下文 link。

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-constraints

您的操作应该如下所示。

    [HttpGet("{id:int}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }