【问题标题】:Task<IActionResult> is getting the wrong valueTask<IActionResult> 得到错误的值
【发布时间】:2021-06-04 09:19:59
【问题描述】:
[ProducesResponseType(200, Type = typeof(OperationResponse<Plan>))]
        [ProducesResponseType(400, Type = typeof(OperationResponse<Plan>))]
        [HttpGet("{id}")]
        public async Task<IActionResult> Get([FromRoute]  string id)
        {
            string userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
            Console.WriteLine("stack is " + t);
            var plan = await _plansService.GetPlanById(id, userId);
            if (plan == null)
                return BadRequest(new OperationResponse<string>
                {
                    IsSuccess = false,
                    Message = "Invalid operation",
                });

            return Ok(new OperationResponse<Plan>
            {
                Record = plan,
                Message = "Plan retrieved successfully!",
                IsSuccess = true,
                OperationDate = DateTime.UtcNow
            });
        }

字符串 id 应该是 guid 类型,而我得到的是“搜索”这个词,而不是 id,它应该是特定产品的 guid。如何跟踪值.... 或映射?

【问题讨论】:

  • 我认为您不了解 RouteParameter 的工作原理:如果您想将 id 作为路由参数传递,您的 url 看起来像:api/plans/guid 而不是 api/plans/search
  • 那么在路由的发生方式上一定存在不匹配?
  • 真的不能说,我只能说你的例子。如果这是您的控制器中唯一的 Get 请求,那么我想它正在尝试路由到该端点。
  • 我们不知道您的预期路线是什么样的,因为您没有发布该代码。我们不知道谁在提出实际请求,以及为什么他们认为他们的路线是正确的。但很明显,两者并不匹配。如果没有更多信息,这个问题无法回答。

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


【解决方案1】:

您的 URL /api/plans/search?query=you&amp;page=1 中没有任何可以解析为 GUID 的内容。大概控制器上的路由前缀是/api/plans/,因此在您的操作中将id 声明为FromRoute,您就有了/api/plans/{id} 的路由。因此,当使用提供的 URL 调用 GET 时,您最终会以“搜索”作为您的 id

您可以尝试以下方法:

[HttpGet("search")]
public async Task<IActionResult> Get([FromQuery] string id)

然后调用如下:

GET /api/plans/search?id=<guid_string>&page=1`

id 然后将被设置为一个可以被解析为 guid 的字符串。

【讨论】:

    【解决方案2】:

    我通过将 api 更改为来修复它

    var response = await client.GetProtectedAsync<ProductsCollectionPagingResponse>($"{_baseUrl}/api/plans/query={query}/page={page}");
    

    来自

     var response = await client.GetProtectedAsync<ProductsCollectionPagingResponse>($"{_baseUrl}/api/plans?query={query}&page={page}");
    

    【讨论】:

    • 在这个例子中,id是哪一个?
    猜你喜欢
    • 2019-08-14
    • 2019-07-30
    • 2017-11-06
    • 1970-01-01
    • 2019-06-17
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多