2010-12-06 158 views
1

我有一个基于实体框架POCO类的简单原型WCF服务。当我运行一个暴露的方法而未指定响应格式时,它将XML格式的预期数据返回给浏览器。但是,如果我指定“ResponseFormat = WebMessageFormat.Json”,则没有数据返回给浏览器。如果我尝试使用Fiddler来查看更多内容,我发现对浏览器的响应是“ReadResponse()失败:服务器没有为此请求返回响应。”WCF服务 - JSON - 没有数据返回

这里是服务合同:

[ServiceContract] 
public interface ITimeService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "/Customer?ID={customerID}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] 
    Customer GetCustomer(string customerID); 

    [OperationContract] 
    [WebGet(UriTemplate = "/Customers", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] 
    List<Customer> GetCustomers(); 

    [OperationContract] 
    [WebGet(UriTemplate = "/Tasks/?CustomerID={customerID}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] 
    List<Task> GetTasks(string customerID); 

} 

和实现:

public Customer GetCustomer(string customerID) 
    { 
     var ID = new Guid(customerID); 
     var context = new PinPointTimeEntities(); 
     var customer = context.Customers.Include("TimePeriods").Include("Tasks").Where(c => c.ID == ID).SingleOrDefault<Customer>(); 
     return customer; 
    } 

    public List<Customer> GetCustomers() 
    { 
     var context = new PinPointTimeEntities(); 
     var customers = context.Customers.ToList(); 
     return customers; 
    } 

    public List<Task> GetTasks(string customerID) 
    { 
     var ID = new Guid(customerID); 
     var context = new PinPointTimeEntities(); 
     var tasks = context.Tasks.Include("TimePeriods").Where(c => c.CustomerID == ID).ToList(); 
     return tasks; 
    } 

我已经尝试了一些没有成功建议的解决方案的。我想这是一个简单的设置或者是需要的。我需要做什么才能以json格式成功返回数据?

+0

你可以发布服务合同,或者至少是你正在使用的方法吗?你还可以发布该服务方法的实现吗? – 2010-12-10 10:33:36

回答

1

我相信这个问题与自引用类有关。从我在上面的场景中可以看到的两种情况,以及尝试使用DataContractJsonSerializer将数据存储在Windows Phone上的隔离存储中时,似乎JSON不处理具有循环引用的序列化类。

0

我知道这个问题已经回答了,但是......

我相信这是因为你的Customer是不可序列。解决这个问题非常简单,只需在您的(公共)数据字段(您想要序列化的)上添加[DataContract]标签到Customer类和[DataMember]标签来创建数据合同。

[DataContract] 
public class Customer { 
    ... 

    [DataMember] 
    public int CustomerID; // this field will show up in the json serialization 

    public string CustomerSIN; // this field will not 

    ... 
} 
0

我有同样的问题,我的wcf服务没有正确格式化JSON,同时将它从数据集转换为Json。我得到它的工作通过使用下述溶液:

using System.ServiceModel.Channels; 
using System.ServiceModel.Web; 

dsData是我的数据集

String JString = Newtonsoft.Json.JsonConvert.SerializeObject(dsData); 
return WebOperationContext.Current.CreateTextResponse(JString, "application/json;charset=utf-8", System.Text.Encoding.UTF8); 

和“消息”将返回类型。