1

In my application, I have a value ("BusinessUnit") which I want to add into every request to a web-service. One way of doing this would be to write a WCF behaviour, which would insert the value for me.

However, the one part I am not clear on is how I can get this value from my application and into the behaviour.

To illustrate my question, here is how I might implement it.

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    string businessUnit = //How do I set this to a value known by the client?
    MessageHeader<string> header = 
        new MessageHeader<string>(businessUnit);
    request.Headers.Add(
        header.GetUntypedHeader("Business Unit", "http://mywebsite.com"));
}

Any ideas?

RB.
  • 36,301
  • 12
  • 91
  • 131

1 Answers1

1

If this value is the same for all calls, then you can consider using a static variable for it. If it varies per call, you can use the operation context to add it (and even skipping the behavior), as shown below

ServiceClient client = new ServiceClient(...);
using (new OperationContextScope(client.InnerChannel))
{
    MessageHeader<string> header = new MessageHeader<string>(businessUnit);
    OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader("Business Unit", "http://mywebsite.com"));
    client.MakeServiceCall();
}

If it's something that varies per group of calls, you can consider passing it to the behavior when you create the client, and then the behavior can pass it to the inspector it creates:

ServiceClient client = new ServiceClient(...);
client.Endpoint.Behaviors.Add(new MyBehavior(businessUnit));
client.MakeServiceCall1();
client.MakeServiceCall2();
client.MakeServiceCall3();
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
  • Thanks for that - the 3rd way is sort of doable. I was hoping to set the behaviour in the web.config though, to avoid changing any code. For the 1st way - the value will be different for all calls. For the 2nd way, I want to use a behaviour so that I can do this across 50+ web-services. – RB. May 27 '11 at 18:28