最新下载
热门教程
- 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项目中也可以用。
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22