问题描述
我有一个客户端代码实现,可以使用IEndpointBehavior使用服务来跟踪请求和响应数据.
I have a client code implementation to consume a service with IEndpointBehavior to track request and response data.
一切正常,直到我使用OperationContextScope实现承载令牌.
everything was working fine till I implement bearer token using 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停止调用,因为我实现了基于令牌的身份验证,并且当我删除用于向标头添加令牌的OperationContextScope代码时,此方法可以正常工作.
BeforeSendRequest, AfterReceiveReply stops calling since I implemented token-based authentication and it is working when I remove OperationContextScope code used for adding a token to the header.
我需要帮助以了解如何一起使用(使用OperationContextScope和IEndpointBehavior用于消息拦截器进行令牌插入).
I need help to understand how can I use both (token inserting using OperationContextScope and IEndpointBehavior for message interceptor) together.
推荐答案
根据您的描述,我进行了测试并成功使用了OperationContextScope和IEndpointBehavior.您可以将OperationContextScope的代码放在IEndpointBehavior的代码之前,将导致IEndpointBehavior的代码失败.
According to your description, I did the test and successfully used OperationContextScope and IEndpointBehavior together.You may put the code of OperationContextScope in front of the code of IEndpointBehavior, which will cause the code of IEndpointBehavior to fail.
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");
上面的代码结构将导致此问题.
The above code structure will cause this problem.
正确的代码结构应如下所示:
The correct code structure should look like this:
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");
这篇关于使用OperationContextScope设置标头时,IClientMessageInspector BeforeSendRequest方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!