2013-04-17 87 views
0

我有一个wcf服务。我需要保存用户并做出回应。这是我的方法:WCF服务的JSON消息格式

[OperationContract] 
    [WebInvoke(UriTemplate = "SaveUsersCode", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] 
    Response SaveUsers(UserCode code); 

UserCode类只有两个字符串属性。我正在使用Google Postman进行检查。我已经尝试了所有内容,并总是收到错误“服务器在处理请求时遇到错误”。

发送JSON消息的正确格式是什么?

+0

'我试过everything'如果我们知道你试过的,我们可以给出更好的答案。 – I4V

+0

我试过{“companyName”:“cocaCola”,“imsi”:“3324”,“msisdn”:“21331”},{companyName:“cocaCola”,“imsi”:3324,msisdn:“21331”} ,'{“companyName”:“cocaCola”,“imsi”:“3324”,“msisdn”:“21331”}',{“UserCode”:[{“companyName”:“cocaCola”,“imsi”:“3324 “,”msisdn“:”21331“}]} – Flipper

+0

看看这个:[为什么我不能用Javascript访问我的WCF web服务?](http://stackoverflow.com/questions/14328466/why-cant -i-access-my-wcf-web-service-with-javascript/14328818#14328818) –

回答

1

翻转我用你的模板

[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); 
} 

当当,它的工作原理

+0

不适合我,我在json上的语法错误仍然很糟糕 - 真的不知道现在什么 – Flipper

+0

现在一切正常。谢谢 – Flipper