Search code examples
c#httpclientwebapi

How to post List<T> through HttpClient?


I've studied a related question and tried to use it in my own case (Blazor Server App). I have the following code:

public async static Task HttpPostAsync(List<Equipment> eqs)
    {
    var myObject = (dynamic)new JsonObject();
    myObject.List = eqs;
    var client = new HttpClient();
    var data = new StringContent(myObject.toString(), Encoding.UTF8, "application/json");
    var response = await 

client.PostAsync("https://localhost:7002/api/ApiEquipment/EquipmentStatusOn", data);
}

When I run the code, I see the following error in the browser console:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Text.Json.Nodes.JsonObject' does not contain a definition for 'List' at CallSite.Target(Closure , CallSite , Object , List`1 )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)

How can I fix that?

Update:

My api code is:

[HttpPost]
public async Task<IActionResult> EquipmentStatusOn([FromBody] List<Equipment> eqs)
{
    foreach (var item in eqs)
    {
        item.IsActive = true;
    }
    await _sqlServerContext.BulkUpdateAsync(eqs, config => config.BatchSize = 200);
    await _sqlServerContext.BulkSaveChangesAsync();

    return Ok(eqs);
}

Solution

  • The error you're getting relates to myObject.List = eqs. You've cast to a dynamic to prevent build errors, but this results in the runtime error you're getting. You'll need to encode the list into JSON, you can use the built-in JsonContent class to handle this for you.

    var myObject = new { List = eqs };
    var client = new HttpClient();
    using var data = JsonContent.Create(myObject)
    var response = await client.PostAsync("https://localhost:7002/api/ApiEquipment/EquipmentStatusOn", data)