开发者

Cannot serialize parameter of type 'System.Linq.Enumerable... ' when using WCF, LINQ, JSON

I have a WCF Service. It uses Linq-to-objects to select from a Dictionary. The object type is simple:

public class User 
{
   public Guid Id;
   public String Name;
}

There is a collection of these stored in a Dictionary<Guid,User>.

I want to have a WCF OperationContract method like this:

public IEnumerable<Guid> GetAllUsers()
{
    var selection = from user in list.Values
        select user.Id;
     return selection;
}

It compiles fine, but when I run it I get:

The server encountered an error processing the request. The exception message is 'Cannot serialize parameter of type 'System.Linq.Enumerable+WhereSelectEnumerableIterator2[Cheeso.Samples.Webservices._2010.Jan.User,System.Guid]' (for operation 'GetAllUsers', contract 'IJsonService') because it is not the exact type 'System.Collections.Generic.IEnumerable1[System.Guid]' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute.'. See server logs for more details.

How can I coerce the selection to be an IEnumerable<Guid> ?


EDIT

If I modify the code to do this, it w开发者_如何学Corks well - good interoperability.

public List<Guid> GetAllUsers()
{
    var selection = from user in list.Values
        select user.Id;
     return new List<Guid>(selection);
}

Is there a way for me to avoid the creation/instantiation of the List<T> ?


No, one must return a concrete class from a web service. Make the return type List and be done with it.


You have to use the ServiceKnownTypes attribute.

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Test.Service
{
    [ServiceContract(Name = "Service", Namespace = "")]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(
            Method = "GET",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        [ServiceKnownType(typeof(List<EventData>))]
        IEnumerable<EventData> Method(Guid userId);
    }
}

Basically you need to know the concrete type of what you're returning. Pretty simple.


You need to pass interoperable collections to and from your WCF methods.

WCF plays best with simple types and arrays.

Pass in an array from your client and then turn it into an IEnumerable in the service.

Stuff like IEnumerable is not interoperable, which is what WCF is trying to be.

There may be a way to get around it with known types, but I always strive to make my components as flexible as possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜