net wcf webinvoke 怎么post请求的json

 我来答
匿名用户
推荐于2016-10-05
展开全部
测试实体类:(需要在客户端和服务端建了有相同字段名称的实体)

public class CompositeType
{
public CompositeType()
{
SubCompositeTypes = new List<SubCompositeType>() { new SubCompositeType() };
}
public bool BoolValue { get; set; }
public string StringValue { get; set; }
public List<SubCompositeType> SubCompositeTypes
{
get;
set;
}
}
public class SubCompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}

客户端请求代码:

#region JosnPost
CompositeType compositeType = new CompositeType
{
StringValue = "1",
BoolValue = false
};

DataContractJsonSerializer dcSerializer = new DataContractJsonSerializer(typeof(CompositeType));

MemoryStream stream = new MemoryStream();

dcSerializer.WriteObject(stream, compositeType);

string data = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);

//HttpClient client = new HttpClient();

//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string link = "http:// localhost:1766/Service1.svc/CreateUser";

//HttpResponseMessage respondse = await client.PostAsync(link, new StringContent(data));

//string dataWithJason = await respondse.Content.ReadAsStringAsync();

var request = (HttpWebRequest)WebRequest.Create(new Uri(link));
request.ContentType = "application/json";
request.Method = "POST";

using (var requestStream = await request.GetRequestStreamAsync())
{
var writer = new StreamWriter(requestStream);
writer.Write(data);
writer.Flush();
}

using (var resp = await request.GetResponseAsync())
{
using (var responseStream = resp.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var result = reader.ReadToEnd();
}
}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式