Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a WCF OperationContext in passing header values via Channel

Tags:

c#

wcf

I have a WCF service which requires an application ID parameter to be passed to each service call. Currently my exposed methods require a parameter. I want to try and push this information into the Channel headers. My WCF is hosted using Net.tcp. Here is my client proxy code:

public class CustomerClient : ClientBase<ICustomerBrowser>, ICustomerBrowser
{
  public Customer Get(string ApplicationID, string CustomerId)
  {
    try
    {
        using (OperationContextScope _scope = new OperationContextScope(this.InnerChannel))
        {
            MessageHeader _header = MessageHeader.CreateHeader("AppID", string.Empty, ApplicationId);
            OperationContext.Current.OutgoingMessageHeaders.Add(_header);
            return Channel.Get(ApplicationId, CustomerId);
            // return Channel.Get(CustomerId);
        }
    }
  }
}

(The commented out line is what I want to use going forward).

Server code:

var _context = WebOperationContext.Current;
var h = _context.IncomingRequest.Headers;

In the _context object there are private methods containing my header, but publicly in the _context.IncomingRequest.Headers I get this:

There is no HttpRequestMessageProperty on the incoming Message.

So my question is, am I suffering because I am not hosting on HTTP? Is there a way to trick the server to give me access to those headers by adding some pseudo HTTP headers? Or can I get at the private members maybe via reflection?

like image 228
Dominic Cotton Avatar asked Feb 26 '16 12:02

Dominic Cotton


1 Answers

You are using the wrong instance of an OperationContext.

The WebOperationContext is specialized for messages that are transported over http. It expects its headers to have a specif name. In the case of WebOperationContext the MessageHeaders dictionary expects a key named httpRequest, which isn't provided in your scenario.

As you're using the standard OperationContext client side should do the same server side:

var _context = OperationContext.Current;
var headers = _context.IncomingMessageHeaders; 
foreach (MessageHeaderInfo h in headers)
{
     if (h.Name == "AppID") {
        Debug.WriteLine(h.ToString());
     }
}
like image 53
rene Avatar answered Oct 31 '22 02:10

rene