1

I have created my channel factory using the following.

var client = GetMyChannelFactory<MyService>();
var myService = client.CreateChannel();
//Add token before this as following method cannot be called by anonymous
var result = myService.GetResult();


internal ChannelFactory<T> GetFirmChannelFactory<T>()
{
    BasicHttpBinding basicHttpBinding = GetBasicHttpBinding();
    string url = "example.com";
    EndpointAddress address = new EndpointAddress(url);
    return new ChannelFactory<T>(basicHttpBinding, address);
}

I have the following token to be added in the header of the WCF request which I am calling.

var token = applicationUser.Token.Result;

I tried adding EndPoint behavior but no success.

How can I add authorization bearer token into the WCF request header?

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60

1 Answers1

1

It seems that you want to add custom Http-headers in the specific request. There are usually two ways to add the HTTP headers.

Uri uri = new Uri("http://10.157.13.69:16666");
            BasicHttpBinding binding = new BasicHttpBinding();
            ChannelFactory<ITestService> factory = new ChannelFactory<ITestService>(binding, new EndpointAddress(uri));
            ITestService service = factory.CreateChannel();
            using (new OperationContextScope((IClientChannel)service))
            {
                //first method to add HTTP header.
                //HttpRequestMessageProperty request = new HttpRequestMessageProperty();
                //request.Headers["MyHttpheader"] = "myvalue";
                //OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = request;
                OperationContext oc = OperationContext.Current;
                WebOperationContext woc = new WebOperationContext(oc);
                woc.OutgoingRequest.Headers.Add("myhttpheader", "myvalue");
                //invocation, only valid in this request.
                var result = service.GetResult();
                Console.WriteLine(result);
            }

Result.
enter image description here
We need to pay attention to that the request along with the specific Http Header is only valid within the OperationContextScope. After the OperationContextScope is released, I.E. the invocation outside of the OperationContextScope does not attach the specific Http Header.
If we want add a persistent HTTP header in every request, we could consider using the below interface.
How to add a custom HTTP header to every WCF call?
Feel free to let me know if there is anything I can help with.

Abraham Qian
  • 7,117
  • 1
  • 8
  • 22