How to add a custom HTTP header to every WCF call?

wcf add soap header to request
how to get request header in wcf service
wcf add authorization header
add http header to soap request c#
wcf test client add headers
how to add request header in rest client c#
dataservicecontext add header
basichttpbinding add header

I have a WCF service that is hosted in a Windows Service. Clients that using this service must pass an identifier every time they're calling service methods (because that identifier is important for what the called method should do). I thought it is a good idea to somehow put this identifier to the WCF header information.

If it is a good idea, how can I add the identifier automatically to the header information. In other words, whenever the user calls the WCF method, the identifier must be automatically added to the header.

UPDATE: Clients that are using the WCF service are both Windows applications and Windows Mobile application (using Compact Framework).

The advantage to this is that it is applied to every call.

Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message. It might look something like this:

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,  System.ServiceModel.IClientChannel channel)
{
    HttpRequestMessageProperty httpRequestMessage;
    object httpRequestMessageObject;
    if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
    {
        httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
        if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
        {
            httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
        }
    }
    else
    {
        httpRequestMessage = new HttpRequestMessageProperty();
        httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
    }
    return null;
}

Then create an endpoint behavior that applies the message inspector to the client runtime. You can apply the behavior via an attribute or via configuration using a behavior extension element.

Here is a great example of how to add an HTTP user-agent header to all request messages. I am using this in a few of my clients. You can also do the same on the service side by implementing the IDispatchMessageInspector.

Is this what you had in mind?

Update: I found this list of WCF features that are supported by the compact framework. I believe message inspectors classified as 'Channel Extensibility' which, according to this post, are supported by the compact framework.

Add custom http header to the request · Issue #3472 · dotnet/wcf , How can I add custom http header to the wcf request in asp.net core? Maybe every wcf requests even? I am trying to follow  HTTP Header. To add an Http header: // Add a HTTP Header to an outgoing request HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty(); requestMessage.Headers["MyHttpHeader"] = "MyHttpHeaderValue"; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage; And to grab it server-side

You add it to the call using:

using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
    MessageHeader<string> header = new MessageHeader<string>("secret message");
    var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
    OperationContext.Current.OutgoingMessageHeaders.Add(untyped);

    // now make the WCF call within this using block
}

And then, server-side you grab it using:

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");

Adding custom http header to all WCF requests, I needed to add a customer http header to the outgoing request of a web service call (for authentication purposes). With old web services it was  How to add a custom HTTP header to every WCF call? (8) I have a WCF service that is hosted in a Windows Service. Clients that using this service must pass an identifier every time they're calling service methods (because that identifier is important for what the called method should do).

If you just want to add the same header to all the requests to the service, you can do it with out any coding! Just add the headers node with required headers under the endpoint node in your client config file

<client>  
  <endpoint address="http://localhost/..." >  
    <headers>  
      <HeaderName>Value</HeaderName>  
    </headers>   
 </endpoint>  

Adding Custom Message Headers to a WCF Service using , Any of these scenarios are candidates for adding a custom header to a WCF Service. First we instantiate a new instance of our WCF Client Proxy. BeforeSendRequest(ref Message request, IClientChannel channel) { . In InterceptAsyncCore, you can await your m_TokenService.GetTokenAsync call, then call methodToInvoke.Invoke. You then cast the result of Invoke to Task and await it. You will need a try/catch around that. Once it's completed, you use reflection to get the Result from the Task and call tcs.SetResult.

Here is another helpful solution for manually adding custom HTTP Headers to your client WCF request using the ChannelFactory as a proxy. This would have to be done for each request, but suffices as a simple demo if you just need to unit test your proxy in preparation for non-.NET platforms.

// create channel factory / proxy ...
using (OperationContextScope scope = new OperationContextScope(proxy))
{
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty()
    {
        Headers = 
        { 
            { "MyCustomHeader", Environment.UserName },
            { HttpRequestHeader.UserAgent, "My Custom Agent"}
        }
    };    
    // perform proxy operations... 
}

How to add a custom HTTP header to every WCF call?, One way would be to pass it as an additional request parameter. But, each and every method call needs to have this parameter(s) repeatedly. Modifying the service client definition to add our extensions. Next step is to use WCF Service Configuration Editor to modify our config file. Right click the web.config file in your client project. Click Edit WCF ConfigurationEdit WCF Configuration. Expand Advanced | Extensions | Behavior element extensions.

This is similar to NimsDotNet answer but shows how to do it programmatically.

Simply add the header to the binding

var cl = new MyServiceClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( 
      AddressHeader.CreateAddressHeader("ClientIdentification",  // Header Name
                                         string.Empty,           // Namespace
                                         "JabberwockyClient"));  // Header Value

cl.Endpoint.Address = eab.ToEndpointAddress();

Add custom headers to a WCF channel, But in WCF, we cannot use the same attribute. One way would be to pass it as an additional request parameter. But, each and every method call  Any of these scenarios are candidates for adding a custom header to a WCF Service. The Quick & Dirty Solution Of course I could just edit method signatures of each service call to accept this additional information as additional parameters but this causes a number of other problems.

Add Custom Message Header in WCF 4 Calls, When a data service requires you to manually set the message header for every request, consider registering the handler for the  1. SOAP Header. The CustomHeader class is used to create custom header for service in which we want to pass header information along with method call. The CustomHeader class contains the information that we want to pass along with method call. You can define the structure as per your needs.

How to: Set Headers in the Client Request (WCF Data Services , software development workflow windows communication foundation wf wcf biztalk server bts services service web service soa service oriented  How to: Set Headers in the Client Request (WCF Data Services) When you use the WCF Data Services client library to access a data service that supports the Open Data Protocol (OData), the client library automatically sets the required HTTP headers in request messages sent to the data service.

WCF: How to append header to HTTP Request?, I have a WCF service that is hosted in a Windows Service. Clients that using this service must pass an identifier every time they're calling service methods  That's really the sole purpose of message contracts: defining the explicit SOAP message layout, including custom headers. See some articles and blog posts on the topic: Adding custom headers to every WCF call - a solution; WCF custom message headers; Add custom headers to a WCF channel. How to add a custom HTTP header to every WCF call?

Comments
  • Were you able to solve your problem?
  • Did you end up getting this to work on the Compact Framework?
  • See: blogs.msdn.microsoft.com/wsdevsol/2014/02/07/…
  • @Mark, This is a really great answer. Thanks. I've tried this over net.tcp but am using the Headers collection directly (the Http Headers didn't work). I get a Header with my token (Name) in at ServiceHost AfterReceiveRequest event, but not the value (there doesn't even seem to be a property for a value?). Is there something I am missing? I would have expected a name/value pair as when I create the header it asks me for: request.Headers.Add(MessageHeader.CreateHeader(name, ns, value));
  • +1 OutgoingMessageProperties are what you need to access HTTP Headers - not OutgoingMessageHeaders which are SOAP headers.
  • Simply, Awesome Code! :)
  • This only allows a hardcoded user agent, which - according to the given example - is hardcoded in the web.config!
  • This is an excellent answer. It also handles the case when the HttpRequestMessageProperty.Name is not yet available in the message properties. For some reason, debugging my code, I realized that depending on some timing issues this value was not always there. Thanks Mark!
  • Thanks for you code-snippet. But with this I have to add the header every time I want to call a method. I wanted to make this process transparent. I mean with implementing once, every time the user creates a service client and used a method, the customer header automatically added to the message.
  • This is a good MSDN link with an example to expand on the suggestion provided in this answer: msdn.microsoft.com/en-us/library/…
  • Thanks, this is a great piece of code if you are using a custom client library. This way you don't need to implement the messageinspector. Just create a common wrapper method which wraps every client call in trhe OperationContextScope.
  • As a note, this is problematic if you're doing any sort of async stuff with your calls, because OperationContextScope (and OperationContext) are ThreadStatic - Mark Good's answer will work without relying on ThreadStatic items.
  • Thank you for the now make the WCF call within this using block