gpt4 book ai didi

c# - 传递 List 时,使用 Param List 的 WCF 调用失败

转载 作者:行者123 更新时间:2023-11-30 22:33:21 24 4
gpt4 key购买 nike

WCF 服务接口(interface):

[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) 错误请求。

如果我将 NULL 传递给“gt.Data”...它工作正常。

注意:

When I put the mouse over the gt.Data ...the hint shows as MyType[]
Not sure if that's expected.

After some review, I noticed that the Client Service only knows about
the 1st [KnownType] stated, in my case the List. No knowledge of List ....
Is that expected when you put various [KnownType] on the WCF Interface?

最佳答案

你需要用 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();

此示例是通过添加服务引用而不是使用共享程序集生成的

关于c# - 传递 List<MyType> 时,使用 Param List<T> 的 WCF 调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8348389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com