我有一个wcf服务。我需要用它来保存用户并做出回应。这是我的方法:
[OperationContract]
[WebInvoke(UriTemplate = "SaveUsersCode", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
Response SaveUsers(UserCode code);
UserCode类只有两个字符串属性。我正在使用Google Postman进行检查。我已经尝试了所有内容并且始终收到错误“服务器遇到处理请求的错误”。
发送JSON消息的正确格式是什么?
答案 0 :(得分:1)
Flipper我使用你的模板编写了一个服务器代码
[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,它可以工作