0

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);
}
Alex Wright
  • 421
  • 1
  • 11

1 Answers1

3

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)
itsdaniel0
  • 1,059
  • 3
  • 11
  • 28
  • I tested this code. The response return status code of 400 (Bad Request). – Alex Wright Feb 20 '23 at 17:13
  • With your edits it looks like it takes an array directly, not an object with a property called `List`. Try sending through `JsonContent.Create(eqs)` instead – itsdaniel0 Feb 20 '23 at 17:15
  • I used `using var data = JsonContent.Create(eqs);`. The response is still 400. – Alex Wright Feb 20 '23 at 17:21
  • I would try to call the endpoint via another tool (such as Postman) to get your request correct, then rebuild that request in C#. – itsdaniel0 Feb 20 '23 at 17:24
  • 1
    If asp.net has rejected your call with a BadRequest the returned body should contain details why. – Ralf Feb 20 '23 at 17:31
  • Do we need to set `Encoding.UTF8` and `application/json` in headers? How can I add them in the final code? – Alex Wright Feb 20 '23 at 17:36
  • 1
    These are the defaults if not provided. You can read more about JSON Content here: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.jsoncontent.create – itsdaniel0 Feb 20 '23 at 17:40