使用 HttpClient 从 Web API 发布 JsonObject [英] POSTing JsonObject With HttpClient From Web API
本文介绍了使用 HttpClient 从 Web API 发布 JsonObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用来自 Web API 的 HttpClient
POST 一个 JsonObject
.我不太确定如何解决这个问题,也找不到太多示例代码.
I'm trying to POST a JsonObject
using HttpClient
from Web API. I'm not quite sure how to go about this and can't find much in the way of sample code.
这是我目前所拥有的:
var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";
HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.Post("", ???);
我想我需要将我的 JsonObject
转换为 StreamContent
但我在这一步上被挂断了.
I think I need to cast my JsonObject
as a StreamContent
but I'm getting hung up on that step.
推荐答案
使用新版本的 HttpClient
而没有 WebApi
包,它将是:
With the new version of HttpClient
and without the WebApi
package it would be:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;
或者如果你想要它async
:
var result = await client.PostAsync(url, content);
这篇关于使用 HttpClient 从 Web API 发布 JsonObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文