Adding custom headers to every WCF call - a solution

Tags: .NET, CodeSnippets, WCF, WinFX, WinFX January CTP

At last, a solution presented itself. While I must admit that at first I was very skeptical of the extensibilty model for WCF which seemed far too involved and complicated, but after implementing a simple extension I must say it's simple and quite intuitive.

My goal was to have several custom headers added to each call made through a proxy, rather than manually adding them to each call's OperationContext. With a little help from Ralph Squillace's blog, I was able to get an extension up and running within minutes, and it Just Works.

The first item to build is the actual extension logic. In this case, I needed an IProxyMessageInspector object that inspects each outgoing message and adds the custom headers:

public class ContextPusher : IProxyMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            // Do nothing.
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageHeader myHeader = new MessageHeader("HeaderValue").GetUntypedHeader("MyHeader", "ns");
            request.Headers.Add(
myHeader);
            return null;
        }
    }
}

Now we want to attach that inspector to proxy. We do that wth Behavior objects. This can be done on an operation-by-operation basis or for all operations on a given channel. We can make the same class implement both behaviors, for flexibility:

public class CallContextAttribute : Attribute, IChannelBehavior, IOperationBehavior
    {
        #region IOperationBehavior Members

        public void ApplyBehavior(OperationDescription description, ProxyOperation proxy, BindingParameterCollection parameters)
        {      
            // Add my MessageInspector to each message sent by the proxy.
            proxy.Parent.MessageInspectors.Add(new ContextPusher());
  
        }

        public void ApplyBehavior(OperationDescription description, DispatchOperation dispatch, BindingParameterCollection parameters)
        {
            // No server-side behaviors for now.
        }

        #endregion
               
        #region IChannelBehavior Members

        public void ApplyBehavior(ChannelDescription description, ProxyBehavior behavior, BindingParameterCollection parameters)
        {
            // Add the MessageInspector to every message sent through the channel.
            behavior.MessageInspectors.Add(new ContextPusher());
        }

        #endregion
    }


And then simply put it on a Service or Operation.
I think in this case, putting the attribute on both will result in an error when trying to add duplicate headers. But this allows me flexibility in adding the headers only to certain calls.

[ServiceContract]
[CallContext]
public interface ILocalizationServices
{
   [OperationContract]
   [CallContext]
   string DoSomething(string param);
}


I think this is the first time I got really excited by the WCF framework and the ease of using and extending it. This is FUN.

74 Comments

  • Vishal said

    Hi Am having same requiremnts i need to pass Headers to 3rd Party Web Service Using WCF. I just know tht the Web service Need some headers which i need to pass. I cant modify Web Service whatevr i have to do is through WCF cleint. Can u please explain the code above i mean ContextPusher & CallContextAttribute shld be the class on Client Application or on Service Side?

  • vishal said

    Hi Can u please send me SERVICE & WCF Client Code. I cant modify 3rd Party Web Service still i want to pass headers using WCF behaviour. Please PLease Help me...if u can mail me the code tht will be of great help am using FEB CTP

  • dalbong2 said

    I found your post today while surfing around the web. This is exactly what i need. Can you send me the code of your sample? My email is hajimaru1@hotmail.com

  • Aaron said

    Hi, This is really cool. I'm also really interested in your client and server side code of this sample. Kindly mail me at, apeterin@yahoo.com Thanks Aaron

  • Sean said

    Thanks for the post. I am trying to follow this and one thing that is making this VERY difficult is that you didn't post the "using" statements that are required to implement this code. Sean

  • Y2KPRABU said

    That was way too old guys in 2006 , lots of classes and interfaces have changed , check the latest code here public class ContextPusher : IClientMessageInspector { public void AfterReceiveReply(ref Message reply, object correlationState) { // Do nothing. } public object BeforeSendRequest(ref Message request, IClientChannel channel) { MessageHeader myHeader = MessageHeader.CreateHeader("MyHeader", "ns", "HeaderValue"); request.Headers.Add(myHeader); return null; } } public class CallContextAttribute : Attribute, IOperationBehavior ,IContractBehavior { #region IOperationBehavior Members void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { } void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { clientOperation.Parent.MessageInspectors.Add (new ContextPusher()); } void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { //throw new NotImplementedException(); } void IOperationBehavior.Validate(OperationDescription operationDescription) { // throw new NotImplementedException(); } #endregion #region IContractBehavior Members void IContractBehavior.AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } void IContractBehavior.ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.MessageInspectors.Add(new ContextPusher()); } void IContractBehavior.ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime) { //throw new NotImplementedException(); } void IContractBehavior.Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) { //throw new NotImplementedException(); } #endregion }

  • Kangkan said

    It seems fine where I am using WCF/.NET on both the sides. But what should one do for interoperable services. In my case, I am writing a service on WCF/.NET and the binding is basicHTTP and I am consuming it from a gSOAP client on a c/Linux ARM processor based device. I wish to send some or all content in the header in encrypted form so that it can not be sniffed. I however don't want to go for HTTPS as it will slow down the transactions. This is so because I am using GPRS to connect from the device and the bandwidth available is simply too poor. Is there some solution for such a scenario?

  • vivek said

    I have tried all possible way to solve this issue from last 10 days. Till issue exist. I am having the below setup. WCF Client WCF Routing Service WCF Service My requirement is need to add the SessionID in the Cookie in the WCF Routing service. I am using the IClientMessageInspector in Routing service as below and adding the HttpRequestMessageProperty properly. Before returning i check that cookie is added. However, at the WCF server side i seen that Message.Properties is not received ( blank). Not sure what is problem. Pupublic 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_COOKIEE])) { httpRequestMessage.Headers[USER_COOKIEE] = this.m_Session; } } else { httpRequestMessage = new HttpRequestMessageProperty(); httpRequestMessage.Headers.Add(USER_COOKIEE, this.m_Session); request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage); } return null; } Also , i tried using the OperationContextScope as below , till unable to send the Custom HTTP headers at WCF service. I checked headers in the Routing service all added headers exist, but when i see at WCF service not there. Please help me to resolve this issue. public object BeforeSendRequest(ref Message request, IClientChannel channel) { get HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, "CookieTestValue"); using (OperationContextScope scope = new OperationContextScope(channel)) //Create scope using the channel. { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; //OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequestProperty); //Also i added transport property as below. OperationContext.Current.OutgoingMessageProperties.Add("TestHeader1"," TestHeaderVal 1213"); } return null } Please let me know what is solution for this issue. Waiting for immediate reply. -vivek

  • Wholesale Jerseys said

    Great blog, very glad to come here. Here I saw a lot. I didn’t see all that before the information, which benefit me a lot. Thanks for sharing, I will pay attention to you, I hope you can post more articles.

  • Woolrich jacket said

    I don't know whether it's just me or if every person else encountering problems with your web page. It appears as though some of the text in your content are running off the screen. Can someone else please comment and let me know if this is happening to them too? This may be a problem with my web browser because I've had this happen before. Cheers!

  • Pickering said

    What i do not understood is in fact how you're now not really a lot more neatly-appreciated than you may be right now. You are very intelligent. You already know thus considerably when it comes to this subject, made me in my view imagine it from so many varied angles. Its like women and men don't seem to be fascinated unless it's one thing to do with Woman gaga! Your personal stuffs outstanding. At all times care for it up!

  • Duckett said

    I've been surfing on-line greater than three hours nowadays, but I never found any interesting article like yours. It's lovely price sufficient for me. Personally, if all website owners and bloggers made just right content as you did, the internet will probably be much more useful than ever before.

  • Cloud said

    I blog quite often and I truly appreciate your content. This great article has truly peaked my interest. I am going to book mark your site and keep checking for new information about once a week. I subscribed to your RSS feed too.

  • Dupre said

    Very nice post. I just stumbled upon your blog and wished to say that I've truly loved surfing around your blog posts. In any case I'll be subscribing in your rss feed and I am hoping you write once more soon! Red Dawn Movie Online

  • Harms said

    Nice weblog right here! Additionally your website so much up very fast! What host are you using? Can I am getting your associate hyperlink in your host? I want my site loaded up as fast as yours lol

  • Peek said

    I am extremely inspired together with your writing talents as neatly as with the format on your weblog. Is this a paid topic or did you modify it yourself? Anyway stay up the nice quality writing, it's uncommon to peer a nice blog like this one nowadays..

  • Dees said

    Today, due to the many opportunities being made available across the web, there have been a great number of ways via which one can get the results that they want and when it comes to finding out how one can get the best of SERP results that will be able to ensure that you can get the best of what you want. Native Rank is a full-service search and advertising solution for Ad Agencies, News Papers, Search Companies and Small to Large Business.

  • Menendez said

    Use your imagination and let your fingers / palms do the rest. For example, out of 183 nonverbal children in two studies, 11 spoke their first words between 5-13 years of age. The digestive and circulatory systems are improved, getting blood flowing through the body. Mike grafstein smt(c) certified sports massage therapistwhat is client handling. Medicare regulations require that physical therapy services be performed either (1) by a state-licensed physical therapist or (2) by or incident to the services of a physician or other medical professional licensed to perform such services under state law pursuant to 42 c!!! You can choose amongst deep tissue massage, indian head massage, chinese massage, shiatsu and so on. It is inspired by three world dance traditions - indian classical dance, ballet and contemporary dance - and is an integrative art form based in the philosophy of ayurveda. Pregnancy massages are best given after the first trimester of pregnancy because the fetus and the mother are still to vulnerable during the early stages.

  • Mcmillan said

    I think the admin of this web site is really working hard in favor of his web page, as here every information is quality based stuff. The Clone Wars Season 5 Episode 12

  • Osgood said

    Woah! I'm really digging the template/theme of this blog. It's simple, yet effective. A lot of times it's challenging to get that "perfect balance" between usability and appearance. I must say you've done a fantastic job with this. Also, the blog loads extremely quick for me on Safari. Excellent Blog!

  • Messer said

    Nice weblog right here! Additionally your web site a lot up very fast! What host are you the use of? Can I am getting your associate link for your host? I desire my site loaded up as quickly as yours lol

  • Billingsley said

    Unquestionably consider that which you stated. Your favourite reason appeared to be at the web the simplest thing to bear in mind of. I say to you, I certainly get annoyed at the same time as people consider concerns that they just do not recognize about. You controlled to hit the nail upon the highest and outlined out the whole thing without having side-effects , folks can take a signal. Will probably be again to get more. Thank you

  • Conyers said

    Aw, this was a really good post. Taking the time and actual effort to create a top notch article… but what can I say… I put things off a whole lot and don't seem to get anything done.

  • Whitman said

    My spouse and I stumbled over here coming from a different web page and thought I might check things out. I like what I see so now i am following you. Look forward to checking out your web page again.

  • Andersen said

    Hi, i think that i saw you visited my website so i came to “return the favor”.I'm attempting to find things to improve my web site!I suppose its ok to use some of your ideas!!

  • Rupert said

    Excellent goods from you, man. I've understand your stuff previous to and you're just too excellent. I really like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I can't wait to read much more from you. This is really a terrific website.

  • Cowan said

    Asking questions are genuinely pleasant thing if you are not understanding something fully, however this piece of writing presents pleasant understanding yet.

  • Marroquin said

    Hi, Neat post. There's a problem along with your web site in web explorer, might test this? IE nonetheless is the marketplace leader and a big section of folks will miss your wonderful writing because of this problem.Watch Scandal Season 2 Episode 11 Online

  • Hildreth said

    Wonderful work! That is the type of information that are supposed to be shared across the web. Shame on the search engines for no longer positioning this post upper! Come on over and discuss with my website . Thanksyou can travel to this site Chaussures Burberry,Burberry Botte,Chemises Burberry, Burberry Homme

  • Catalano said

    What is essential is that the medication or techniques that one does are secure and allows in the scenario and not to damage the individual. Garlic's several beneficial center results are due to not only its sulfur substances, but also to its supplement C, supplement B6, selenium and manganese. Of course, their partner will know that their man is having a difficulty with male impotence, which for the men makes the matter worse.

  • Wester said

    Excellent blog here! Also your website loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

  • Hairston said

    You made some good points there. I looked on the internet for additional information about the issue and found most people will go along with your views on this web site.

  • Cano said

    My programmer is trying to convince me to move to . net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using WordPress on several websites for about a year and am nervous about switching to another platform. I have heard good things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any kind of help would be greatly appreciated!

  • Aponte said

    Wow, incredible weblog format! How long have you ever been running a blog for? you made running a blog look easy. The full glance of your site is excellent, let alone the content material!

  • Mccool said

    Thanks for any other informative website. Where else may I get that kind of information written in such a perfect method? I have a project that I'm just now operating on, and I have been on the glance out for such info.

  • Oglesby said

    I really like what you guys tend to be up too. This kind of clever work and coverage! Keep up the great works guys I've incorporated you guys to my personal blogroll.

  • Craven said

    Fantastic beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog web site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea

  • Conover said

    Hi, i think that i noticed you visited my web site so i got here to go back the want? .I am trying to find things to enhance my site!I assume its ok to make use of some of your concepts!!

  • Winter said

    Hello, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you reduce it, any plugin or anything you can recommend? I get so much lately it's driving me crazy so any assistance is very much appreciated.

  • Nowak said

    Definitely imagine that which you said. Your favourite justification appeared to be at the web the simplest factor to be mindful of. I say to you, I certainly get annoyed whilst folks consider worries that they just do not realize about. You managed to hit the nail upon the top and also outlined out the entire thing without having side-effects , other people could take a signal. Will probably be again to get more. Thanks

  • Hood said

    It's a pity you don't have a donate button! I'd certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will talk about this site with my Facebook group. Talk soon!

Comments have been disabled for this content.