2013-04-17 158 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