Asp.net XML反序列化提供空WCF对象

Asp.net XML反序列化提供空WCF对象,asp.net,wcf,Asp.net,Wcf,我有一个XML字符串,比如 <?xml version="1.0"?> <FullServiceAddressCorrectionDelivery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <AuthenticationInfo xmlns="http://www.usps.com/postalone/se

我有一个XML字符串,比如

<?xml version="1.0"?>
<FullServiceAddressCorrectionDelivery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AuthenticationInfo xmlns="http://www.usps.com/postalone/services/UserAuthenticationSchema">
    <UserId xmlns="">FAPushService</UserId>
    <UserPassword xmlns="">Password4Now</UserPassword>
  </AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>
对于反序列化,我使用xmlserializer反序列化对象

XmlSerializer xs = new XmlSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.Deserialize(stream);
此方法返回空的FullServiceAddressCorrectionDelivery对象。。 但是当我使用DataContractSerializer。。像

DataContractSerializer xs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.ReadObject(stream);
然后出现了以下例外情况

第2行第46位出错。应为命名空间中的元素“FullServiceAddressCorrectionDelivery”http://schemas.datacontract.org/2004/07/WcfService1'.. 遇到名称为“FullServiceAddressCorrectionDelivery”的“元素”,命名空间为“”

我被这个困住了。。。
在RENE(StackOverFlow成员)的帮助下,我成功地反序列化了同一个项目中的类。。但是当我把它们转换成WCF数据合同时。。我遇到了那个问题。。。。。请告诉我我哪里做错了

根据您希望如何使用数据协定序列化程序(DCS)进行该输入,您可以这样做,也可以不这样做。DC中数据成员的名称空间由其所属合约的名称空间定义,除非它是根元素(在这种情况下,[DC]名称空间也定义了元素的名称空间)

根元素FullServiceAddressCorrectionDelivery在示例XML中有一个名称空间(空),其成员AuthenticationInfo有另一个名称空间(http://www.usps.com/postalone...). 这意味着,除非您实际更改序列化程序的创建方式,否则您将无法将DCS用于此类型

然而,XmlSerializer(XS)应该可以正常工作——该类型的成员可以有不同的名称空间。正如您在下面的代码中所看到的,我可以将您提供的XML逐字发布到一个操作,该操作将FullServiceAddressCorrectionDelivery作为输入,并且对象已正确填充-您需要使用[XmlSerializerFormat]属性标记该操作(或契约)以获得此行为

public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a
{
    const string XML = @"<?xml version=""1.0""?>
 <FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
 xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
   <AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
     <UserId xmlns="""">FAPushService</UserId>
     <UserPassword xmlns="""">Password4Now</UserPassword>
   </AuthenticationInfo>
 </FullServiceAddressCorrectionDelivery>";

    [XmlRoot(ElementName = "FullServiceAddressCorrectionDelivery", Namespace = "")]
    public class FullServiceAddressCorrectionDelivery
    {
        [XmlElement("AuthenticationInfo", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
        [DataMember]
        public AuthenticationInfo AuthenticationInfo { get; set; }
    }

    public class AuthenticationInfo
    {
        [XmlElement("UserId", Namespace = "")]
        public string UserId { get; set; }

        [XmlElement("UserPassword", Namespace = "")]
        public string UserPassword { get; set; }
    }

    [ServiceContract(Namespace = "")]
    public interface ITest
    {
        [XmlSerializerFormat]
        [OperationContract]
        FullServiceAddressCorrectionDelivery Echo(FullServiceAddressCorrectionDelivery input);
    }

    public class Service : ITest
    {
        public FullServiceAddressCorrectionDelivery Echo(FullServiceAddressCorrectionDelivery input)
        {
            return input;
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        c.Headers[HttpRequestHeader.ContentType] = "text/xml";
        Console.WriteLine(c.UploadString(baseAddress + "/Echo", XML));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
public class Post_6fc3a1bd_b3ca_48da_b4d2_352711358a
{
常量字符串XML=@“
FAPushService
密码4Now
";
[XmlRoot(ElementName=“FullServiceAddressCorrectionDelivery”,Namespace=”“)]
公共类FullServiceAddressCorrectionDelivery
{
[XmlElement(“AuthenticationInfo”,命名空间=”http://www.usps.com/postalone/services/UserAuthenticationSchema")]
[数据成员]
公共身份验证info AuthenticationInfo{get;set;}
}
公共类身份验证信息
{
[xmlement(“UserId”,Namespace=”“)]
公共字符串用户标识{get;set;}
[XmlElement(“用户密码”,名称空间=”)]
公共字符串UserPassword{get;set;}
}
[ServiceContract(名称空间=”)]
公共接口测试
{
[XmlSerializerFormat]
[经营合同]
FullServiceAddressCorrectionDelivery回显(FullServiceAddressCorrectionDelivery输入);
}
公共类服务:ITest
{
公共FullServiceAddressCorrectionDelivery回显(FullServiceAddressCorrectionDelivery输入)
{
返回输入;
}
}
公共静态无效测试()
{
string baseAddress=“http://“+Environment.MachineName+”:8000/服务”;
WebServiceHost主机=新的WebServiceHost(类型(服务),新的Uri(基地址));
host.Open();
Console.WriteLine(“主机已打开”);
WebClient c=新的WebClient();
c、 标题[HttpRequestHeader.ContentType]=“text/xml”;
WriteLine(c.UploadString(baseAddress+“/Echo”,XML));
控制台。写入(“按ENTER键关闭主机”);
Console.ReadLine();
host.Close();
}
}
为了完整性起见,这就是如何更改序列化程序创建(传递根名称和命名空间),以便能够反序列化使用数据协定序列化程序提供的XML

public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a_b
{
    const string XML = @"<?xml version=""1.0""?>
 <FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
 xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
   <AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
     <UserId xmlns="""">FAPushService</UserId>
     <UserPassword xmlns="""">Password4Now</UserPassword>
   </AuthenticationInfo>
 </FullServiceAddressCorrectionDelivery>";

    [DataContract(Name = "FullServiceAddressCorrectionDelivery", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
    public class FullServiceAddressCorrectionDelivery
    {
        [DataMember]
        public AuthenticationInfo AuthenticationInfo { get; set; }
    }

    [DataContract(Name = "AuthenticationInfo", Namespace = "")]
    public class AuthenticationInfo
    {
        [DataMember]
        public string UserId { get; set; }

        [DataMember]
        public string UserPassword { get; set; }
    }

    static string Serialize(object obj, bool useDataContractSerializer)
    {
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = false,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        if (useDataContractSerializer)
        {
            var dcs = new DataContractSerializer(obj.GetType(), "FullServiceAddressCorrectionDelivery", "");
            dcs.WriteObject(w, obj);
        }
        else
        {
            new XmlSerializer(obj.GetType()).Serialize(w, obj);
        }

        w.Flush();
        string result = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(result);

        w.Close();
        ms.Close();
        return result;
    }

    public static void Test()
    {
        Console.WriteLine("Serialization:");
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = false,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        var dcs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery), "FullServiceAddressCorrectionDelivery", "");

        var obj = new FullServiceAddressCorrectionDelivery
        {
            AuthenticationInfo = new AuthenticationInfo
            {
                UserId = "FAPushService",
                UserPassword = "Password4Now"
            }
        };

        dcs.WriteObject(w, obj);

        w.Flush();
        string result = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(result);
        Console.WriteLine();

        Console.WriteLine("Deserialization:");
        ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));

        var obj2 = (FullServiceAddressCorrectionDelivery)dcs.ReadObject(ms);
        Console.WriteLine("{0} - {1}", obj2.AuthenticationInfo.UserId, obj2.AuthenticationInfo.UserPassword);
    }
}
public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a_b
{
常量字符串XML=@“
FAPushService
密码4Now
";
[DataContract(Name=“FullServiceAddressCorrectionDelivery”,命名空间=”http://www.usps.com/postalone/services/UserAuthenticationSchema")]
公共类FullServiceAddressCorrectionDelivery
{
[数据成员]
公共身份验证info AuthenticationInfo{get;set;}
}
[DataContract(Name=“AuthenticationInfo”,Namespace=”“)]
公共类身份验证信息
{
[数据成员]
公共字符串用户标识{get;set;}
[数据成员]
公共字符串UserPassword{get;set;}
}
静态字符串序列化(对象obj,bool useDataContractSerializer)
{
MemoryStream ms=新的MemoryStream();
XmlWriterSettings ws=新的XmlWriterSettings
{
缩进=真,
缩进字符=”,
OmitXmlDeclaration=false,
编码=新的UTF8编码(错误)
};
XmlWriter w=XmlWriter.Create(ms,ws);
如果(使用DataContractSerializer)
{
var dcs=新的DataContractSerializer(obj.GetType(),“FullServiceAddressCorrectionDelivery”,和“”);
dcs.WriteObject(w,obj);
}
其他的
{
新的XmlSerializer(obj.GetType()).Serialize(w,obj);
}
w、 冲洗();
字符串结果=Encoding.UTF8.GetString(ms.ToArray());
控制台写入线(结果);
w、 Close();
Close女士();
返回结果;
}
公共静态无效测试()
{
Console.WriteLine(“序列化:”);
MemoryStream ms=新的MemoryStream();
XmlWriterSettings ws=新的XmlWriterSettings
{
缩进=真,
缩进字符=”,
OmitXmlDeclaration=false,
编码=新的UTF8编码(错误)
};
XmlWriter w=XmlWriter.Create(ms,ws);
var dcs=新的DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery),“FullServiceAddressCorrectionDelivery”,和“”);
var obj=新的完整版本
public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a_b
{
    const string XML = @"<?xml version=""1.0""?>
 <FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
 xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
   <AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
     <UserId xmlns="""">FAPushService</UserId>
     <UserPassword xmlns="""">Password4Now</UserPassword>
   </AuthenticationInfo>
 </FullServiceAddressCorrectionDelivery>";

    [DataContract(Name = "FullServiceAddressCorrectionDelivery", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
    public class FullServiceAddressCorrectionDelivery
    {
        [DataMember]
        public AuthenticationInfo AuthenticationInfo { get; set; }
    }

    [DataContract(Name = "AuthenticationInfo", Namespace = "")]
    public class AuthenticationInfo
    {
        [DataMember]
        public string UserId { get; set; }

        [DataMember]
        public string UserPassword { get; set; }
    }

    static string Serialize(object obj, bool useDataContractSerializer)
    {
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = false,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        if (useDataContractSerializer)
        {
            var dcs = new DataContractSerializer(obj.GetType(), "FullServiceAddressCorrectionDelivery", "");
            dcs.WriteObject(w, obj);
        }
        else
        {
            new XmlSerializer(obj.GetType()).Serialize(w, obj);
        }

        w.Flush();
        string result = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(result);

        w.Close();
        ms.Close();
        return result;
    }

    public static void Test()
    {
        Console.WriteLine("Serialization:");
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = false,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        var dcs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery), "FullServiceAddressCorrectionDelivery", "");

        var obj = new FullServiceAddressCorrectionDelivery
        {
            AuthenticationInfo = new AuthenticationInfo
            {
                UserId = "FAPushService",
                UserPassword = "Password4Now"
            }
        };

        dcs.WriteObject(w, obj);

        w.Flush();
        string result = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(result);
        Console.WriteLine();

        Console.WriteLine("Deserialization:");
        ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));

        var obj2 = (FullServiceAddressCorrectionDelivery)dcs.ReadObject(ms);
        Console.WriteLine("{0} - {1}", obj2.AuthenticationInfo.UserId, obj2.AuthenticationInfo.UserPassword);
    }
}