Search code examples
c#reactjsasp.net-web-apihttp-postfetch-api

Can't pass an array of numbers to HttpPost method using fetch api


I want to pass two properties to the backend, one is a number, and another is a number[].

In the backend, I have a function with the HTTP POST method:

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

And I am trying to call it using 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()}`)
}

But I get status 400 with the error that says:

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

This is what the JSON looks like:

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

What could be the problem?


Solution

    1. Create a model class with the properties that you will pass from the front-end.
    public class UpdateUserSubscriptionsModel
    {
        public int InfocenterId { get; set; }
        public int[] Subscriptions { get; set; }
    }
    
    1. Modify the UpdateUserSubscriptions parameter to expect to receive an object of the UpdateUserSubscriptionsModel type.
    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);
        }
    }
    

    Reference: Using [FromBody]