首页 > 解决方案 > 将 HTTP Get 中的 Int[] 传递给 CoreWebAPI

问题描述

我有一个 Blazor WebAssembly 托管项目,需要发布一个 Id 数组来获取。

[AllowAnonymous]
[HttpGet("GetByTypePaged/{ingredientTypeIds}/{startIndex}/{count}/{search?}")]
public async Task<IActionResult> GetByTypePaged([FromQuery]int[] ingredientTypeIds, int startIndex, int count, string? search)

然而, IngredientTypeIds 以 int[0] 的形式返回,因此没有检索到任何 Id。我试过 FromRoute,我得到了 415 以及没有 FromQuery

名称空间中不存在 FromUri

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

Id 必须安装 Microsoft.AspNet.WebApi.Core nuget 包才能获取 System.Web.Http 命名空间。然而,随后

[Authorize]
[Route]
[HttpGet] 

等等 System.Web.Http 和 AspNetCore 之间都有歧义。如果我删除对 Microsoft.AspNetCore 的引用,那么我会为我的 HttpPut 操作丢失 [FromBody]。

public async Task<IActionResult> Update(int id, [FromBody] Ingredient ingredient)

我最好的方法是什么

标签: c#asp.net-core-webapiblazor-webassembly

解决方案


[HttpGet("GetByTypePaged/{ingredientTypeIds}/{startIndex}/{count}/{search?}")]

在您的代码中,我们可以发现您定义了一个带有路由参数ingredientTypeIdsstartIndexcount可选参数的路由search

请注意,路由数据和查询字符串值仅用于简单类型,如果您想在 URL 中传递一个 Id 数组并绑定到操作参数int[] ingredientTypeIds,您可以修改您的路由并以这种格式通过查询字符串传递它:

ingredientTypeIds[0]=1&ingredientTypeIds[1]=2

此外,如果你想将复杂类型的数据传递给你的后端 API,你可以让你的端点支持 HTTP POST 方法,你可以通过请求体传递预期的数据。


推荐阅读