将标头添加到.Net 3.5 WCF客户端

时间:2012-08-06 21:14:46

标签: c# .net wcf header client

我在c#.Net framework 3.5中有一个简单的Web客户端,可以像这样调用SOAP服务HelloWorld:

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

我正在使用一些通过请求授权标题来增加基本安全性的中间件:“授权=承载123456abcd”,它与REST服务一起使用,但我想使用上面的.Net客户端来使用该服务...

如何将标头添加到服务呼叫? 是否存在类似:myservice.addHeader("authorization=blah");

的内容

1 个答案:

答案 0 :(得分:3)

您应该使用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();
      }

授权

var messageProperty = new HttpRequestMessageProperty();
messageProperty.Headers.Add(HttpRequestHeader.Authorization, AuthorizationHeader);