我有一个要求,我必须使用 System.Object 作为 WCF 中的参数。由于它不可序列化,因此我收到消息,因为它使用 System.Object,因此不支持该操作。这个问题的任何解决方案。
问问题
6460 次
1 回答
5
当通过网络发送消息时,默认情况下,WCF 只会序列化足以传递消息的内容,即合同的成员。如果您的消息将“对象”作为参数,则需要通过网络发送带有类型信息的额外信息。如果在客户端和服务器上使用相同的程序集,则可以在服务器(和客户端)中使用 NetDataContractSerializer(而不是默认的 DataContractSerializer),它们将能够交换任意对象,如代码所示以下。但是,正如@MarcGravell 提到的,这可能不是 WCF 的最佳用法......
启用的代码NetDataContractSerializer
:
public class Post_8b2c7ad7_b1c3_410b_b907_f25cee637110
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("Person[Name={0},Age={1}]", Name, Age);
}
}
[ServiceContract]
public interface ITest
{
[OperationContract]
object Echo(object obj);
}
public class Service : ITest
{
public object Echo(object obj)
{
return obj;
}
}
public class ReplaceSerializerOperationBehavior : DataContractSerializerOperationBehavior
{
public ReplaceSerializerOperationBehavior(OperationDescription operation)
: base(operation)
{
}
public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
{
return new NetDataContractSerializer(name, ns);
}
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
{
return new NetDataContractSerializer(name, ns);
}
public static void ReplaceSerializer(ServiceEndpoint endpoint)
{
foreach (var operation in endpoint.Contract.Operations)
{
for (int i = 0; i < operation.Behaviors.Count; i++)
{
if (operation.Behaviors[i] is DataContractSerializerOperationBehavior)
{
operation.Behaviors[i] = new ReplaceSerializerOperationBehavior(operation);
break;
}
}
}
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
var endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
ReplaceSerializerOperationBehavior.ReplaceSerializer(endpoint);
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ReplaceSerializerOperationBehavior.ReplaceSerializer(factory.Endpoint);
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Echo("Hello"));
Console.WriteLine(proxy.Echo(123.456));
Console.WriteLine(proxy.Echo(new Uri("http://tempuri.org")));
Console.WriteLine(proxy.Echo(new Person { Name = "John Doe", Age = 33 }));
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
于 2012-05-29T01:10:09.887 回答