WCF服务引用返回类型自动转为数组[],调整设置无效求解决方案
解决WCF服务引用返回类型自动转为数组的问题
问题背景
WCF服务的操作契约定义返回IList<Employee>,服务实现返回List<Employee>,但在Web项目添加服务引用后,生成的代理方法返回类型被自动转为Employee[]。修改服务引用高级设置为使用System.Collections.Generic.List并重新加载后,问题仍未解决。
服务契约代码:
[OperationContract(Name = "GetAllEmployee")] IList<Employee> GetEmployees(string UserId, string UserPassword);
服务实现代码:
public IList<Employee> GetEmployees(string UserId, string UserPassword) { List<Employee> E = new List<Employee>(); return E; }
生成的代理代码返回数组:
public ServiceWeb.ServiceProWCFService.Employee[] GetAllEmployee(string UserId, string UserPassword) { ServicePROWeb.ServiceProWCFService.GetAllEmployeeRequest inValue = new ServicePROWeb.ServiceProWCFService.GetAllEmployeeRequest(); inValue.UserId = UserId; inValue.UserPassword = UserPassword; ServicePROWeb.ServiceProWCFService.GetAllEmployeeResponse retVal = ((ServicePROWeb.ServiceProWCFService.IServiceProWCFService)(this)) .GetAllEmployee(inValue); return retVal.GetAllEmployeeResult; }
解决方案
1. 显式指定服务契约的集合类型
修改服务契约,直接返回List<Employee>而非IList<Employee>,同时添加ServiceKnownType标记确保序列化识别集合类型:
首先确认Employee类已标记DataContract:
[DataContract] public class Employee { [DataMember] public int EmployeeId { get; set; } // 其他业务属性... }
更新服务契约:
[ServiceContract] [ServiceKnownType(typeof(List<Employee>))] public interface IServiceProWCFService { [OperationContract(Name = "GetAllEmployee")] List<Employee> GetEmployees(string UserId, string UserPassword); }
服务实现同步修改返回类型(保持逻辑不变):
public List<Employee> GetEmployees(string UserId, string UserPassword) { List<Employee> E = new List<Employee>(); return E; }
重新发布服务后,删除Web项目旧服务引用并重新添加。
2. 手动修改服务引用的配置文件
找到Web项目中服务引用的Reference.svcmap文件(路径:Service References/[你的服务引用名]/Reference.svcmap),更新<CollectionMappings>节点:
<CollectionMappings> <CollectionMapping TypeName="System.Collections.Generic.List`1" Category="List" /> </CollectionMappings>
保存后右键服务引用选择「更新服务引用」。
3. 使用svcutil.exe手动生成代理
通过命令行工具手动生成代理类,强制指定集合类型:
svcutil.exe http://你的服务地址/ServiceWeb.svc /collectionType:System.Collections.Generic.List`1 /out:ServiceProxy.cs /config:ServiceProxy.config
将生成的ServiceProxy.cs添加到Web项目,并把ServiceProxy.config中的配置合并到项目的web.config中。
4. 检查服务端序列化配置
确保服务端web.config启用了足够的序列化支持:
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
内容的提问来源于stack exchange,提问作者KG_DEV
相关产品推荐
相关产品推荐

