WCF调用与参数列表<传递List时失败
本文关键字:MyType 失败 List 传递 参数 列表 WCF 调用 | 更新日期: 2023-09-27 18:16:18
WCF服务接口:
[ServiceContract]
public interface ITest
{
[OperationContract]
int TestCall(GenericType<MyType> x);
[OperationContract]
int TestAnotherCall(GenericType<MyOtherType> x);
}
[DataContract(Name = "GenericType")]
[KnownType(typeof(List<MyType>))]
[KnownType(typeof(List<MyOtherType>))]
public class GenericType<T>
{
[DataMember]
public List<T> Data
{
get { return data; }
set { data = value; }
}
}
WCF服务实现:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Test : ITest
{
public int TestCall(GenericType<MyType> x)
{
return x.Data.Count;
}
public int TestAnotherCall(GenericType<MyOtherType> x)
{
return x.Data.Count;
}
}
List<MyType> list = from a in ctx.Table
select new MyType (a.Field1, a.Field2, a.Field3).ToList();
GenericType gt = new GenericType();
gt.Data = list;
using(WCFClient client = new WCFClient())
{
client.TestCall(gt);
client.Close();
}
错误:
远程服务器返回了一个意外的响应:(400)Bad Request.
如果我传递NULL给"gt.Data"…
注意:
当我把鼠标放在get . data上…提示显示为MyType[]
我不确定这是否符合预期。经过一些审查,我注意到客户端服务只知道
第一个[已知类型]所述,在我的情况下是列表。不了解List ....
当你把各种[KnownType]放在WCF接口上时,这是预期的吗?
你需要用KnownType()
属性来修饰你的泛型
[DataContract(Name = "GenericType")]
[KnownType(typeof(MyType))]
public class GenericType<T>
{
[DataMember]
public List<T> Data
{
get { return data; }
set { data = value; }
}
}
快速工作示例:
[OperationContract]
GenericType<MyType> GetDataUsingDataContract(GenericType<MyType> composite);
public class Service1 : IService1
{
public GenericType<MyType> GetDataUsingDataContract(GenericType<MyType> composite)
{
composite.Data.First().Stuff = "Test";
return composite;
}
}
[DataContract(Name = "GenericType")]
[KnownType(typeof (MyType))]
public class GenericType<T>
{
[DataMember]
public List<T> Data { get; set; }
}
public class MyType
{
public string Stuff { get; set; }
}
var client = new Service1Client();
var genericType = new GenericType
{
Data = new[]
{
new MyType(),
}
};
var result = client.GetDataUsingDataContract(genericType);
client.Close();
Console.WriteLine(result.Data.First().Stuff);
Console.ReadLine();
此示例是通过添加服务引用而不使用共享程序集生成的
您需要将GenericType属性与它可以包含的每个类的KnownType属性相关联。
例如:[KnownType(typeof(List<MyType>)]
public class GenericType<T>
问题可能是您在实例化GenericType
时没有为T
提供类型。试试这个:
GenericType<MyType> gt = new GenericType<MyType>();
不是GenericType gt = new GenericType();
与实例化任何其他泛型类时的语法相同。例如,要声明一个字符串列表(list as in List<T>
…看这里)你会说:
List<String> myStrings = new List<String>();