IClientMessageInspector BeforeSendRequest method is not working when setting header using OperationContextScope

时光怂恿深爱的人放手 提交于 2021-01-28 18:45:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!