2015-04-27 87 views
0

当我返回时Employee类正常工作,但我只需要几个属性,所以我试图使它在浏览器上得到ERR_CONNECTION_REFUSED,但在代码后面没有错误。返回服务中的json对象

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "employees")] 
    public object GetEmployees() 
    { 
     var c = Employee.GetList().Select(x => new { id = x.Id, title = x.Title, person = x.FullName}); 
     return c; 
    } 


    [OperationContract] 
    object GetEmployees(); 

WebConfig

<service name="FOO.FOO.FOOService"> 
    <endpoint address="http://localhost:8733/FOOService" binding="webHttpBinding" contract="FOO.FOO.IFOOService" /> 
    <host> 
     <baseAddresses> 
     <add baseAddress="http://localhost:8733/FOOService" /> 
     </baseAddresses> 
    </host> 
    </service> 
</services> 
<behaviors> 
    <endpointBehaviors> 
    <behavior> 
     <webHttp /> 
    </behavior> 
    </endpointBehaviors> 
+0

多放些细节到你的问题(确切的错误信息,错误位置等) –

+0

更新,这是我的所有的信息。现在,即使你可以建立一个样本项目来测试。 – Mert

回答

3

你不能用默认的WCF串行使用匿名类型。如果您想要支持匿名类型,则必须创建自定义消息格式化程序(https://msdn.microsoft.com/en-us/library/ms733844.aspx)。

在你的情况,我建议创建EmployeeDTO(雇员数据传输对象)类型,其中将包括要从服务回报领域。然后,您可以将此类型用作GetEmployees方法的返回类型。

+0

我试图避免这样做:/ – Mert

+0

我可以理解这种感觉:)因为你可能会得到很多DTO对象。另一方面,这些DTO对象的编写和维护非常简单。所以它们(在我看来)优于定制的消息格式器。 – drax

0

如果你真的不希望创建一个数据传输对象,这将是我的偏好,那么我建议你返回从服务Dictionary<string,string>对象的列表。虽然有办法让WCF序列化与无类型的对象一起工作,但它们都不可维护或优雅。使用字典应该给你相同的灵活性,没有这些问题。然后

你的代码可以改写为:

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "employees")] 
public List<Dictionary<string, string>> GetEmployees() 
{ 
    var c = Employee.GetList().Select(x => new Dictionary<string, string> {{"id", x.Id.ToString()}, {"title",x.Title}, {"person", "x.FullName"}}).ToList(); 
    return c; 
} 

不要忘了投字典的结果返回给你想要的类型的客户端上。 我也建议在回答考虑看看这个问题: Passing an instance of anonymous type over WCF为什么通过匿名类型在导线的解释是一个坏主意。