.net - IEndpointBehavior ApplyClientBehavior 方法在行为添加到端点行为后未执行

标签 .net wcf soap

鉴于这两个类:

public class InspectorBehavior : IEndpointBehavior
{
    public MessageInspector MessageInspector;

    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters){}
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher){}
    public void Validate(ServiceEndpoint endpoint){}

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        MessageInspector = new MessageInspector();
        clientRuntime.MessageInspectors.Add(MessageInspector);
    }
}

public class MessageInspector : IClientMessageInspector
{
    public string LastRequestXML { get; private set; }
    public string LastResponseXML { get; private set; }
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        LastResponseXML = reply.ToString();
    }

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        LastRequestXML = request.ToString();
        return request;
    }
}

而这个行为初始化代码:
var requestInterceptor = new InspectorBehavior();
MYSoapClient.Endpoint.Behaviors.Add(requestInterceptor);

为什么会这样ApplyClientBehavior方法永远不会执行并且 MessageInspector总是空的?

不应该ApplyClientBehavior当行为被添加到端点行为集合时被执行(我验证它是并且 requestInterceptor 变量不为空)?

最佳答案

就我而言,我使用 wcf for .net core 遇到了这个问题。

在创建 wcf 客户端后设置 EndpointBehaviors 属性时,未调用方法 ApplyClientBehavior。

对我来说有什么技巧:我必须在 wcf 客户端构造函数中设置 EndpointBehaviors 属性。不过,我不能说出这样做的原因,这对我来说根本没有意义,但它确实有效。

如果需要,您可以创建一个新的分部类并使用新的构造函数来注册此行为。如果您需要重新生成服务契约(Contract),这可能很有用。

希望这可以帮助别人。

关于.net - IEndpointBehavior ApplyClientBehavior 方法在行为添加到端点行为后未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119448/

相关文章:

javascript - 通过 C# 在 EmailTemplate.html 中打印数组

c# - 值类型有 Type 对象吗?

c# - Windows.Forms 助记符不起作用

.net - Entity Framework 自定义查询功能

wcf - 如何限制使用WCF服务的用户

java - 如何向 SOAP HEader 中的 childNode 添加子节点?

asp.net - Microsoft.Extensions.Logging 如何在完整的 .net 框架中工作?

c# - 如何最大化大对象堆中最大的连续内存块

c# - 使用 UWP 将信息保存到 SOAP

c# - 从 IClientMessageInspector 登录时屏蔽敏感信息