问题
I have a client code implementation to consume a service with IEndpointBehavior to track request and response data.
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 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.
I need help to understand how can I use both (token inserting using OperationContextScope and IEndpointBehavior for message interceptor) together.
回答1:
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");
来源:https://stackoverflow.com/questions/62344937/iclientmessageinspector-beforesendrequest-method-is-not-working-when-setting-hea