Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Header to .Net 3.5 WCF Client

I have a simple web client in c# .Net framework 3.5 that calls a SOAP service HelloWorld like this:

HelloService myservice = new HelloService();
string result = myservice.HelloWorld();

I am using some middle-ware that adds basic security by asking for an Authorization Header: "Authorization=Bearer 123456abcd" which works with a REST service, but I wanted to consume the service with the .Net client above...

How can I add the header to the Service Call? Does exists something like: myservice.addHeader("authorization=blah");?

like image 314
nuvio Avatar asked Mar 07 '26 00:03

nuvio


1 Answers

You should use OperationContextScope

using (OperationContextScope scope = new OperationContextScope(wcfClient.InnerChannel))
      {
        MessageHeader header
          = MessageHeader.CreateHeader(
          "Service-Bound-CustomHeader",
          "http://Microsoft.WCF.Documentation",
          "Custom Happy Value."
          );
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        // Making calls.
        Console.WriteLine("Enter the greeting to send: ");
        string greeting = Console.ReadLine();

        //Console.ReadLine();
        header = MessageHeader.CreateHeader(
            "Service-Bound-OneWayHeader",
            "http://Microsoft.WCF.Documentation",
            "Different Happy Value."
          );
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        // One-way
        wcfClient.Push(greeting);
        this.wait.WaitOne();

        // Done with service. 
        wcfClient.Close();
        Console.WriteLine("Done!");
        Console.ReadLine();
      }

For Authorization

var messageProperty = new HttpRequestMessageProperty();
messageProperty.Headers.Add(HttpRequestHeader.Authorization, AuthorizationHeader);
like image 159
GSerjo Avatar answered Mar 09 '26 13:03

GSerjo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!