0

When I do return Employee class works fine but what I need only couple properties so I am trying to make it work like this which gets ERR_CONNECTION_REFUSED on browser but no error on code behind.

    [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>
Mert
  • 6,432
  • 6
  • 32
  • 68

2 Answers2

3

You can't use anonymous types with default WCF serializers. If you want to support anonymous types, you have to create custom message formatter (https://msdn.microsoft.com/en-us/library/ms733844.aspx).

In your case, I recommend to create EmployeeDTO (employee data transfer object) type, which would contain fields you want to return from service. You can then use this type as return type for GetEmployees method.

Marian Polacek
  • 2,906
  • 4
  • 30
  • 37
  • I was trying to avoid to do that :/ – Mert Apr 27 '15 at 10:03
  • I can understand the feeling :) since you will probably end up with lots of DTO objects. On the other hand, those DTO objects are very simple to write and maintain. So they are (in my opinion) superior to custom message formatters. – Marian Polacek Apr 27 '15 at 10:25
0

If you really don't want to create a Data Transfer Object, which would be my preference, then I'd recommend returning a list of Dictionary<string,string> objects from the service. Whilst there are ways to get WCF serialization to work with untyped objects, none of them are maintainable or elegant. Using a Dictionary should give you the same flexibility without these problems.

Your code could then be rewritten as:

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

Don't forget to cast the results of the dictionary back to your desired types on the client. I'd also recommend taking a look at the answers to this question: Passing an instance of anonymous type over WCF for an explanation of why passing anonymous types over the wire is a bad idea.

Community
  • 1
  • 1
joelimus
  • 39
  • 8