使用ID作为字符串和int处理WebApi Core方法

时间:2019-05-26 09:01:47

标签: c# asp.net-web-api asp.net-core asp.net-core-2.1

我有两种方法:

    [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的回复

2 个答案:

答案 0 :(得分:2)

您可以定义参数类型,例如[HttpGet("{id:int}")]。有关更多信息,请参见下面的链接。

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

答案 1 :(得分:1)

像这样使用

[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