WCF服务的JSON消息格式
本文关键字:消息 格式 JSON 服务 WCF | 更新日期: 2023-09-27 18:09:36
我有wcf服务。我需要用它保存用户并做出响应。这是我的方法:
[OperationContract]
[WebInvoke(UriTemplate = "SaveUsersCode", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
Response SaveUsers(UserCode code);
UserCode类只有两个字符串属性。我用谷歌邮差检查。我尝试了所有方法,但总是得到一个错误"服务器在处理请求时遇到错误"。
发送JSON消息的正确格式是什么?
我用你的模板写了一个服务器代码
[ServiceContract]
public class MyServer
{
public void Start()
{
Task.Factory.StartNew(() =>
{
WebServiceHost ws = new WebServiceHost(this.GetType(), new Uri("http://0.0.0.0/Test"));
ws.Open();
});
}
[OperationContract]
[WebInvoke(UriTemplate = "SaveUsersCode", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
string SaveUsers(UserCode code)
{
return "GOT: " + code.companyName + "," + code.imsi;
}
public class UserCode
{
public string companyName;
public string imsi;
}
}
并命名为
//Start server
var m = new MyServer();
m.Start();
Task.Delay(1000);
//Call server method
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
var obj = new { companyName = "cocaCola",imsi="3324" };
string response = wc.UploadString("http://localhost/Test/SaveUsersCode", new JavaScriptSerializer().Serialize(obj));
Console.WriteLine(response);
}
ta-da, it Works