无法使用 fetch api 将数字数组传递给 HttpPost 方法

问题描述 投票:0回答:1

我想传递两个属性到后端,一个是

number
,另一个是
number[]

在后端我有一个带有 HTTP POST 方法的函数:

public async Task<IActionResult> UpdateUserSubscriptions(int infocenterId, int[] subscriptions)
        {
            try
            {
                int rowsAffected = await repo.UpdateUserSubscriptionsAsync(infocenterId, subscriptions);

                return Ok(rowsAffected);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

我正在尝试使用 fetch 来调用它:

 async UpdateUserSubscriptionsAsync(infocenterId: number, subscriptions: number[]): Promise<void> {

        var resp = await fetch(`api/Improvements/UpdateUserSubscriptions`, {
            method: 'POST',
            body: JSON.stringify({
                infocenterId: infocenterId,
                subscriptions: subscriptions
            }),
            headers: { "Content-Type": "application/json" },
            credentials: "include"
        })

        if (resp.status >= 400) throw new Error(`[ImprovementsDbHandler UpdateUserSubscriptionsAsync]: ${await resp.text()}`)
    }

但我收到状态 400 并显示以下错误:

The JSON value could not be converted to System.Int32[]

JSON 如下所示:

{"infocenterId":320,"subscriptions":[9,11]}

可能是什么问题?

c# reactjs http-post fetch-api
1个回答
0
投票
  1. 使用将从前端传递的属性创建一个模型类。
public class UpdateUserSubscriptionsModel
{
    public int InfocenterId { get; set; }
    public int[] Subscriptions { get; set; }
}
  1. 修改
    UpdateUserSubscriptions
    参数以期望接收
    UpdateUserSubscriptionsModel
    类型的对象。
public async Task<IActionResult> UpdateUserSubscriptions([FromBody] UpdateUserSubscriptionsModel model)
{
    try
    {
        int rowsAffected = await repo.UpdateUserSubscriptionsAsync(model.InfocenterId , model.Subscriptions );

        return Ok(rowsAffected);
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.