外部 (java) 应用程序向我们的网络服务发送消息。此消息包含多个命名空间:
<StUF:Fo01Bericht xmlns:StUF="http://www.egem.nl/StUF/StUF0300">
<LVO:stuurgegevens xmlns:LVO="http://www.vrom.nl/StUF/sector/lvo/0305">
<StUF:versieStUF>0300</StUF:versieStUF>
<StUF:berichtcode>Fo01</StUF:berichtcode>
</LVO:stuurgegevens>
<StUF:body>
<StUF:code>200</StUF:code>
<StUF:plek>LVO</StUF:plek>
<StUF:omschrijving>test</StUF:omschrijving>
</StUF:body>
</StUF:Fo01Bericht>
WCF 服务无法反序列化此消息,因为第二行有 LVO 前缀(根据 WSDL,它应该是 StUF)。
我想让我们的网络服务接受这些消息。有没有办法做到这一点 - 最好使用属性?
最佳答案
我在接受来自第三方的 soap 消息时遇到了这个问题。
这是我发送的 soapHeader(注意 UsernameToken 中的不同命名空间):
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wssu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>userName</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">password</wsse:Password>
<wsse:Nonce>nonce</wsse:Nonce>
<wssu:Created>2015-02-19T16:24:32Z</wssu:Created>
</wsse:UsernameToken>
</wsse:Security>
为了正确反序列化,我需要在我的 DataContract 中实现 IxmlSerializable,如下所示:
[DataContract(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", Name = "Security")]
public partial class SecurityHeaderType
{
[XmlElementAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
[DataMember]
public UsernameToken UsernameToken { get; set; }
}
public class UsernameToken : IXmlSerializable
{
public string Username { get; set; }
public string Password { get; set; }
public string Nonce { get; set; }
public string Created { get; set; }
public XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
Dictionary<string, string> secDictionary;
string xml = reader.ReadOuterXml();
using (var s = GenerateStreamFromString(xml))
{
secDictionary =
XElement.Load(s).Elements()
.ToDictionary(e => e.Name.LocalName, e => e.Value);
}
Username = secDictionary["Username"];
Password = secDictionary["Password"];
Nonce = secDictionary["Nonce"];
Created = secDictionary["Created"];
}
然后我可以反序列化我的标题,如下所示:
if (OperationContext.Current.IncomingMessageHeaders.FindHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") != -1)
{
var securityHeader = OperationContext.Current.IncomingMessageHeaders.GetHeader<SecurityHeaderType>("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
}
关于c# - WCF - 反序列化时控制命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7121465/