使用 OperationContextScope 设置 header 时,IClientMessageInspector BeforeSendRequest 方法不起作用

IClientMessageInspector BeforeSendRequest method is not working when setting header using OperationContextScope

我有一个客户端代码实现来使用带有 IEndpointBehavior 的服务来跟踪请求和响应数据。

一切正常,直到我使用 OperationContextScope 实现不记名令牌。

var httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer " + accessToken;

            var context = new OperationContext(client.InnerChannel);
            context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
            var operationContext = new OperationContextScope(context);

BeforeSendRequest,AfterReceiveReply 停止调用,因为我实施了 token-based 身份验证,当我删除用于向 header 添加令牌的 OperationContextScope 代码时它正在工作。

我需要帮助来了解如何同时使用这两者(使用 OperationContextScope 和 IEndpointBehavior 插入令牌作为消息拦截器)。

根据你的描述,我做了测试,成功使用了OperationContextScope和IEndpointBehavior together.You可能会将OperationContextScope的代码放在IEndpointBehavior的代码前面,会导致IEndpointBehavior的代码执行失败。

           Service1Client service1Client = new Service1Client();


            var httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer";
            var context = new OperationContext(service1Client.InnerChannel);
            context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
            var operationContext = new OperationContextScope(context);

            service1Client.Endpoint.Behaviors.Add(new Interceptor());
            service1Client.GetUserData("Test");

上面的代码结构会导致这个问题

正确的代码结构应该是这样的:

            Service1Client service1Client = new Service1Client();
            service1Client.Endpoint.Behaviors.Add(new Interceptor());

            var httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer";
            var context = new OperationContext(service1Client.InnerChannel);
            context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
            var operationContext = new OperationContextScope(context);


            service1Client.GetUserData("Test");