直接上代码,使用StringContent Post Json结构数据

 StringContent stringContent = new StringContent(myObjectAsJSON, Encoding.UTF8, "application/json");
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri(endpointUri);
        using (HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(endpointDirectory, stringContent).ConfigureAwait(false))
        {
            // Do something
        }
    }

 

补充说明

  • StringContent 的第二个参数是编码,第三个参数是 Content-Type;发 JSON 必须写 application/json,否则服务端可能拒绝解析。
  • 需要其它头时用 content.Headers.ContentType.CharSet = "utf-8" 补充。
  • 用 HttpClient 时建议复用同一个实例(或 IHttpClientFactory),不要每次 new,避免端口耗尽。
  • 新版 .NET 可直接用 PostAsJsonAsync / ReadFromJsonAsync 简化写法。

相关阅读

参考资料