Reputation: 6582
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>
Upvotes: 0
Views: 415
Reputation: 39
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.
Upvotes: 0
Reputation: 2925
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.
Upvotes: 3