1

可能重复:
WCF:数据合同正在转换为消息合同

我有一个通用的 WCF 代理,对于那些不熟悉它的人来说,它是一个具有以下 OperationContract 的方法的类。

[OperationContract(Action = "*", ReplyAction = "*")]
void Proxy(Message requestMessage);

最近出现的要求之一是,我需要将 Message 中所有类型为 IPAddress 的属性替换为提供请求消息的那些属性的 IPAddress 值。

即类似的东西,

public void Proxy(Message requestMessage)
{
    try
    {
        // Client IP address, not currently used!
        IPAddress clientIP = IPAddress.Parse((requestMessage
            .Properties[RemoteEndpointMessageProperty.Name] 
            as RemoteEndpointMessageProperty).Address);
        var factory = new ChannelFactory<IDmzProxy>("client");
        IDmzProxy dmzProxy = factory.CreateChannel();
        dmzProxy.Proxy(requestMessage);
        factory.Close();
    }

    // No leakage of data!  Any exceptions still return void!
    catch (Exception exception)
    {
        Log.Fatal(
            "Exception occurred on proxying the request",
            exception);
        return;
    }
}

现在的问题是如何将 requestMessage 中 IPAddress 类型的元素设置为我检索到的 clientIP?

编辑 1

我尝试过但失败的事情,

requestMessage.GetBodyAttribute("ipAddress", "http://schemas.datacontract.org/2004/07/System.Net")

编辑 2

一种方法似乎是替换 MessageBody 的 XML。这对我来说似乎有点矫枉过正(那么 WCF 的意义何在?)。

这也不是特别容易,因为 MessageBody 需要通过其属性名称而不是元素名称来匹配元素。

  <ipAddress xmlns:a="http://schemas.datacontract.org/2004/07/System.Net" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:m_Address>3772007081</a:m_Address>
    <a:m_Family>InterNetwork</a:m_Family>
    <a:m_HashCode>0</a:m_HashCode>
    <a:m_Numbers xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
      <b:unsignedShort>0</b:unsignedShort>
    </a:m_Numbers>
    <a:m_ScopeId>0</a:m_ScopeId>
  </ipAddress>

编辑 3

当然不是重复的,这是大致工作的东西,还需要一些工作来替换我所追求的节点,

    public void Proxy(Message requestMessage)
    {
        try
        {
            Log.Info("Received request");
            requestMessage = SourceNATMessage(requestMessage);

            // Check if there is an accepted action we have to catch
            // If the Accepted Action is set, and the action is not the same
            // then just return);)
            if (!String.IsNullOrEmpty(AcceptedAction) &&
                !requestMessage.Headers.Action.EndsWith(AcceptedAction))
            {
                Log.WarnFormat(
                    "Invalid request received with the following action {0}\n" +
                    "expected action ending with {1}",
                    requestMessage.Headers.Action,
                    AcceptedAction);
                return;
            }

            // otherwise, let's proxy the request
            Log.Debug("Proceeding with forwarding the request");
            var factory = new ChannelFactory<IDmzProxy>("client");
            IDmzProxy dmzProxy = factory.CreateChannel();
            dmzProxy.Proxy(requestMessage);
            factory.Close();
        }

        // No leakage of data!  Any exceptions still return void!
        catch (Exception exception)
        {
            Log.Fatal(
                "Exception occurred on proxying the request",
                exception);
            return;
        }
    }

    private static Message SourceNATMessage(Message message)
    {
        IPAddress clientIp =
                IPAddress.Parse(
                    ((RemoteEndpointMessageProperty)
                     message.Properties[
                         RemoteEndpointMessageProperty.Name]).Address);

        Log.DebugFormat("Retrieved client IP address {0}", clientIp);

        var stringBuilder = new StringBuilder();
        XDocument document;

        using (XmlWriter writer = XmlWriter.Create(stringBuilder))
        {
            message.WriteBody(writer);
            writer.Flush();
            document = XDocument.Parse(stringBuilder.ToString());
        }

        var deserializer = new DataContractSerializer(typeof(IPAddress));

        foreach (XElement element in
            from element in document.DescendantNodes().OfType<XElement>()
            let aNameSpace = element.GetNamespaceOfPrefix("a")
            let iNameSpace = element.GetNamespaceOfPrefix("i")
            where
                aNameSpace != null &&
                aNameSpace.NamespaceName.Equals(SystemNetNameSpace) &&
                iNameSpace != null &&
                iNameSpace.NamespaceName.Equals(XmlSchemaNameSpace) &&
                deserializer.ReadObject(element.CreateReader(), false) is IPAddress
            select element)
        {
            element.ReplaceWith(new XElement(element.Name, deserializer.WriteObject());
        }

        return Message.CreateMessage(message.Version,
                                     message.Headers.Action,
                                     document.CreateReader());
    }

编辑 4

对于那些感兴趣的人来说,工作代码不能在问题结束时作为答案发布。

private static Message SourceNatMessage(Message message)
{
    IPAddress clientIp =
            IPAddress.Parse(
                ((RemoteEndpointMessageProperty)
                    message.Properties[
                        RemoteEndpointMessageProperty.Name]).Address);

    Log.DebugFormat("Retrieved client IP address {0}", clientIp);

    var stringBuilder = new StringBuilder();
    XDocument document;

    using (XmlWriter writer = XmlWriter.Create(stringBuilder))
    using (XmlDictionaryWriter dictionaryWriter =
        XmlDictionaryWriter.CreateDictionaryWriter(writer))
    {
        message.WriteBodyContents(dictionaryWriter);
        dictionaryWriter.Flush();
        document = XDocument.Parse(stringBuilder.ToString());
    }

    var deserializer = new DataContractSerializer(typeof(IPAddress));
    var clientIpXml = new StringBuilder();
    using (var xmlWriter = XmlWriter.Create(clientIpXml))
    {
        deserializer.WriteObject(xmlWriter, clientIp);
        xmlWriter.Flush();
    }

    var clientElement = XElement.Parse(clientIpXml.ToString());

    foreach (XElement element in
        from element in document.DescendantNodes().OfType<XElement>()
        let aNameSpace = element.GetNamespaceOfPrefix("a")
        let iNameSpace = element.GetNamespaceOfPrefix("i")
        where
            aNameSpace != null &&
            aNameSpace.NamespaceName.Equals(SystemNetNameSpace) &&
            iNameSpace != null &&
            iNameSpace.NamespaceName.Equals(XmlSchemaNameSpace) &&
            element.NodeType == XmlNodeType.Element
        select element)
    {
        try
        {
            deserializer.ReadObject(element.CreateReader(), false);
            element.ReplaceNodes(clientElement);
        }
        catch (SerializationException) { }
    }

    Message sourceNatMessage = Message.CreateMessage(message.Version,
                                    null,
                                    document.CreateReader());
    sourceNatMessage.Headers.CopyHeadersFrom(message);
    sourceNatMessage.Properties.CopyProperties(message.Properties);

    return sourceNatMessage;
}
4

2 回答 2

0

在正常情况下,您不必这样做。您的消息已经包含您正在寻找的信息。

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

在 endpointProperty.Address 属性上找到客户端 IP 地址,在 endpointProperty.Port 属性上找到端口。

于 2012-06-28T13:11:42.740 回答
0

只需使用自定义寻址标头注释您的 SOAP 消息。

于 2012-06-28T11:25:34.147 回答