2015-08-22 227 views
1

我试图创建WCF REST服务”,我发现 here.C# - 客户端的WCF REST服务JSON

我增加了服务的参考,我写了这个代码的简单客户端:

private void button1_Click(object sender, EventArgs e) 
{ 


    WebClient proxy = new WebClient(); 
    string serviceURL = 
      string.Format("http://localhost:53215/IBookService.svc/GetBooksNames"); 
    byte[] data = proxy.DownloadData(serviceURL); 
    Stream stream = new MemoryStream(data); 
    DataContractJsonSerializer obj = 
     new DataContractJsonSerializer(typeof(finalProject_ClientX.ServiceReference3.Book)); 
    finalProject_ClientX.ServiceReference3.Book book = obj.ReadObject(stream) as finalProject_ClientX.ServiceReference3.Book; 
    MessageBox.Show("book ID : " + book.BookName); 

} 

当我运行的代码(按下按钮),我收到以下错误:

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll

Additional information: The type 'finalProject_ClientX.ServiceReference3.Book' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.

当我在我的本本浏览器中运行“http://localhost:53215/IBookService.svc/GetBooksNames”:

"["MVC Music Store - Tutorial - v3.0","Pro.ASP.NET.MVC.3.Framework","Application Architecture Guide v2","Gang of Four Design Patterns","CS4 Pocket Reference"]"

什么问题?

+0

您是否拥有该服务? –

+0

@PrestonGuillot在哪里?在客户端? – user3868442

+0

如您所说,您是否拥有您所引用服务的定义?你能改变它的合同吗? –

回答

0

好像实体框架包含属性IsReference = true,当它添加属性DataContract。

因此,我建议您在您的项目中包含JSON.Net nuget包。 然后将您的代码修改为类似于:

private void button1_Click(object sender, EventArgs e) 
{ 
    WebClient proxy = new WebClient(); 
    string serviceURL = 
      string.Format("http://localhost:53215/IBookService.svc/GetBooksNames"); 
    byte[] data = proxy.DownloadData(serviceURL); 

    var jsonString = Encoding.UTF8.GetString(data); 
    IList<string> bookNames = JArray.Parse(jsonString).ToObject<IList<string>>(); 

    //Do something with the list 
    //foreach (string bookName in bookNames) 
    //{ 

    //}  
} 
+0

'IsReference'默认为false。 –

+0

我试图改变它......但我也得到一个错误。 “System.dll中发生类型'System.Net.WebException'的未处理异常 其他信息:远程服务器返回错误:(500)内部服务器错误。 ” – user3868442