使用WCF,LINQ,JSON时,无法序列化'System.Linq.Enumerable ...'类型的参数

Che*_*eso 7 linq wcf linq-to-objects json

我有一个WCF服务.它使用Linq-to-objects从Dictionary中进行选择.对象类型很简单:

public class User 
{
   public Guid Id;
   public String Name;
}
Run Code Online (Sandbox Code Playgroud)

有一个存储在一个集合Dictionary<Guid,User>.

我想有一个OperationContract像这样的WCF 方法:

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

编译很好,但是当我运行它时,我得到:

服务器遇到处理请求的错误.异常消息是'无法序列化类型的参数'System.Linq.Enumerable + WhereSelectEnumerableIterator 2[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]'在方法签名中,并且不在已知类型集合中.为了序列化参数,请使用ServiceKnownTypeAttribute将类型添加到操作的已知类型集合中.请参阅服务器日志以获取更多详

我如何强制选择成为一个IEnumerable<Guid>


编辑
如果我修改代码来做到这一点,它运作良好 - 良好的互操作性.

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

有没有办法让我避免创建/实例化List<T>

Che*_*eso 11

不,必须从Web服务返回具体类.创建返回类型列表并完成它.


A-D*_*ubb 5

您必须使用ServiceKnownTypes属性。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,您需要知道所返回内容的具体类型。很简单