我使用XSD2Code从给定的XSD生成C#代码。此工具生成的代码剪切如下:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Orders
{
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public int OrderID {get;set;}
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
public string Description {get;set;}
}
Coud有人请指导下面的队列,请
如果我保留上面的代码,WCF会序列化上面的类吗? 目前我在wcf测试客户端上收到此错误:“”此操作不是 在WCF测试客户端“。
我是否需要在上面生成的代码之上添加DataContract和DataMember?
答案 0 :(得分:3)
[XmlSerializerFormat]
属性[XmlSerializerFormat]
修饰合同,则会忽略DataContract / DataMember属性(而是使用XML序列化属性,例如此类型的属性)XmlSerializer
允许您完全控制序列化类型的XML; DataContractSerializer
(DCS)没有(它更受限制)。但DCS具有更好的性能,因此哪一种更好取决于您的情况。下面的代码显示了使用此类型的服务,即使使用WcfTestClient,它也能正常工作。
public class StackOverflow_7155154
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Orders
{
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public int OrderID { get; set; }
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
public string Description { get; set; }
}
[ServiceContract]
[XmlSerializerFormat]
public interface ITest
{
[OperationContract]
Orders GetOrders();
}
public class Service : ITest
{
public Orders GetOrders()
{
return new Orders { Description = "My order", OrderID = 1 };
}
}
public static void Test()
{
//MemoryStream ms = new MemoryStream();
//XmlSerializer xs = new XmlSerializer(typeof(Orders));
//Orders o = new Orders { OrderID = 1, Description = "My order" };
//xs.Serialize(ms, o);
//Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.GetOrders());
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}