最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Post请求Json格式数据到WCF服务
时间:2022-06-25 08:39:44 编辑:袖梨 来源:一聚教程网
测试实体类:(需要在客户端和服务端建了有相同字段名称的实体)
public class CompositeType
{
public CompositeType()
{
SubCompositeTypes = new List
}
public bool BoolValue { get; set; }
public string StringValue { get; set; }
public List
{
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();
}
}
服务端接口定义:
[OperationContract]
[WebInvoke(
UriTemplate = "CreateUser",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
Method = "POST")]
string CreateUser(CompositeType compositeType);
服务端接口实现:
public string CreateUser(CompositeType compositeType)
{
return "OK" + compositeType.StringValue + " " + compositeType.BoolValue + " " + compositeType.SubCompositeTypes.FirstOrDefault().StringValue;
}
由于服务端需要实现REST服务,需要在web.config里重新配置下(cover serviceModel就可以了):
经测试,在windows runtime项目中也可以用。
相关文章
- 《无限暖暖》织衣蛛获得方法 12-26
- 《无限暖暖》美食家蜜蜂获得方法 12-26
- 《无限暖暖》泳镜蝽获得方法 12-26
- 《无限暖暖》芭蕾豆娘获得方法 12-26
- 《无限暖暖》刺绣蛾获得方法 12-26
- 《无限暖暖》尖帽仙获得方法 12-26