从Web API使用HttpClient发布JsonObject [英] POSTing JsonObject With HttpClient From Web API

查看:107
本文介绍了从Web API使用HttpClient发布JsonObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Web API中的HttpClient来发布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.

这是我到目前为止所拥有的:

Here's what I have so far:

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

这篇关于从Web API使用HttpClient发布JsonObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆