【问题标题】:How to post List<T> through HttpClient?如何通过 HttpClient 发布 List<T>?
【发布时间】:2023-02-21 01:07:02
【问题描述】:

我研究了一个相关的question,并尝试在我自己的案例(Blazor Server App)中使用它。我有以下代码:

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

当我运行代码时,我在浏览器控制台中看到以下错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Text.Json.Nodes.JsonObject' 不包含定义 CallSite.Target 处的“列表”(Closure、CallSite、Object、List`1)
在 System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite 网站,T0 arg0,T1 arg1)

我该如何解决?

【问题讨论】:

    标签: c# httpclient webapi


    【解决方案1】:

    您遇到的错误与myObject.List = eqs 有关。您已转换为动态以防止构建错误,但这会导致您遇到运行时错误。 您需要将列表编码为 JSON,您可以使用内置的 JsonContent 类来为您处理。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多