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>?
您必须使用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)
基本上,您需要知道所返回内容的具体类型。很简单
| 归档时间: |
|
| 查看次数: |
9710 次 |
| 最近记录: |