首页 > 解决方案 > WCF 自定义客户端检查器

问题描述

一家外部公司给了我一个 WSDL 供我使用,它有几个奇怪的特性,我不想影响我的客户端代码。

首先,每个都OperationContract需要发送相同的用户名参数。我不想每次都在我的客户端代码中设置它,而是在全局范围内执行此操作。

我相信将它设置在 aIClientMessageInspector中是我最好的选择,但是,由于这是一个 SOAP 服务,我对如何将它添加到正文中有点困惑。

public class CustomInspector : IClientMessageInspector
{
    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        // Add an additional parameter to the SOAP body

        return null;
    }
}

其次,虽然服务确实返回了映射对象,但其中一个对象包含一个塞入 CDATA 的 xml 文档 :(

<a:ResponseData>

     <![CDATA[ INSERT XML DOCUMENT HERE]]>

</a:ResponseData>

我正在寻找提取 XML 并在没有 CDATA 和 XML 声明的情况下将其重新添加,以便我可以在我的响应对象上添加适当的属性。这样它应该像正常一样反序列化(希望这是有道理的)

public class CustomInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        // Get the XML from the ResponseData element and remove the CDATA. Add the XML back in (Minus the <xml> declaration)   
    }
}

标签: wcf

解决方案


Firstly, each OperationContract requires the same username parameter sent over. Instead of setting this each time in my client code I'd like to do this globally. I believe setting this in a IClientMessageInspector is my best bet, however, with this being a SOAP service I'm a little confused at how to add this into the body.

If you want to add custom message header to the message, you could refer to the following code.

public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
{
    request.Headers.Add(MessageHeader.CreateHeader("username", "", "user"));
    request.Headers.Add(MessageHeader.CreateHeader("password", "", "pass"));
    return null;
}

Take a look at IClientMessageInspector.

Here are some links may be useful to you.

Adding custom SOAP headers from Silverlight client

https://weblogs.asp.net/paolopia/handling-custom-soap-headers-via-wcf-behaviors

https://social.msdn.microsoft.com/Forums/vstudio/en-US/f1f29779-0121-4499-a2bc-63ffe8025b21/wcf-security-soap-header


推荐阅读