Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations

Adding custom headers to every WCF call - a solution

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.

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?
# May 5, 2006 5:16 AM

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

# May 5, 2006 6:57 AM

Saran said:

Hi, can u share this code?

# July 3, 2008 7:31 AM

Smith said:

How can we read this header from Server side??

# September 2, 2008 10:10 AM

Henry said:

This is exactly what I want to do, too.  Can you send me the client and server code?

My email is henrylyyang@yahoo.com

--Henry

# January 6, 2009 2:38 PM

Jim Meehan said:

Can you send me the sample client and server code? Thanks, jb_meeh@yahoo.com

# March 9, 2009 2:29 PM

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

# June 26, 2009 5:07 AM

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

# July 30, 2009 1:24 AM

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

# October 16, 2009 5:52 PM

Dean said:

Please send source Code, this looks awesome and exactly what I need.

# February 8, 2010 9:56 AM

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

   }

# February 11, 2010 8:22 AM

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?

# April 27, 2010 4:56 AM

bhuvan said:

send me the code for custom headers accessing form hotmail or gmail or any server..bhuvan.ram@hotmail.com

# October 8, 2010 5:13 AM

bmw said:

Would you send me your code at bmw_abc@hotmail.com? Thanks.

# October 19, 2010 6:57 PM

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 <===TCP Binding==> WCF Routing Service <==== basicHTTPBinding====> 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

# April 19, 2011 9:56 AM

Denis Kochnev said:

Hi,

I am currently working with WCF Framework 4. I added 2 options how to do it.

# May 22, 2011 4:10 PM

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.

# May 29, 2012 5:02 AM

Pitcher said:

I visit day-to-day some web sites and information sites to

read content, however this webpage gives

feature based articles.

# August 20, 2012 6:31 AM

crork said:

bYt3Rb Major thankies for the blog post. Really Cool.

# October 26, 2012 8:44 AM

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!

# November 12, 2012 8:59 AM

Seo Service said:

ilBR1W A round of applause for your blog post.Much thanks again. Awesome.

# November 25, 2012 1:37 PM

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!

# December 5, 2012 7:43 AM

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.

# December 21, 2012 10:43 AM

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.

# December 22, 2012 1:02 PM

Dunlap said:

Genuinely when someone doesn't be aware of after that its up to other viewers that they will help, so here it occurs.

# December 25, 2012 11:32 PM

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

# December 26, 2012 12:55 PM

Garza said:

Health - A Great Intro

# December 26, 2012 5:38 PM

Bledsoe said:

This is a topic that is near to my heart... Best wishes! Exactly where are your contact details though?

Leverage Season 5 Episode 15

# December 26, 2012 7:29 PM

Sauer said:

This is my first time visit at here and i am truly impressed to read everthing

at single place.

# December 27, 2012 12:26 PM

Clarkson said:

The Options For Basic Details Inside Car Shipping

# December 29, 2012 4:33 AM

Mitchell said:

This is a topic that is close to my heart... Take care!

Exactly where are your contact details though?

# January 1, 2013 9:04 PM

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

# January 2, 2013 4:35 AM

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..

# January 3, 2013 1:11 AM

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.

# January 3, 2013 6:12 AM

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.

# January 5, 2013 12:07 AM

Samuels said:

Here those on! First time I hear!

# January 5, 2013 1:19 PM

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

# January 6, 2013 5:47 AM

Christianson said:

Yes! Finally something about bags uk.

# January 6, 2013 6:57 AM

Reedy said:

It's amazing for me to have a website, which is good in support of my know-how. thanks admin

# January 7, 2013 2:24 AM

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!

# January 8, 2013 6:02 AM

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

# January 10, 2013 7:10 PM

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

# January 11, 2013 8:50 AM

Zeigler said:

Incredible quest there. What occurred after? Good luck!

# January 11, 2013 3:47 PM

Olivas said:

Quality articles is the key to attract the viewers to visit the web page, that's what this web page is providing.Watch Underemployed Season 1 Episode 12

# January 13, 2013 12:39 AM

Bouchard said:

If you are going for most excellent contents like

I do, simply go to see this web site everyday as it provides feature contents, thanks

# January 13, 2013 7:39 AM

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.

# January 14, 2013 1:56 AM

Sell said:

Greetings! Very helpful advice within this article!

It's the little changes that produce the most significant changes. Thanks a lot for sharing!

# January 14, 2013 4:31 AM

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.

# January 15, 2013 2:23 PM

Chance said:

What's up mates, how is the whole thing, and what you desire to say on the topic of this paragraph, in my view its really remarkable for me.

# January 15, 2013 6:51 PM

Mccurry said:

At this time I am ready to do my breakfast, later than having

my breakfast coming over again to read further news.

# January 16, 2013 6:00 AM

Roe said:

You ought to take part in a contest for one of the highest quality blogs on the net.

I will recommend this blog!

# January 16, 2013 9:46 AM

Bernal said:

Very shortly this web page will be famous among all

blogging and site-building viewers, due to it's fastidious articles

# January 16, 2013 2:28 PM

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!!

# January 16, 2013 5:13 PM

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.

# January 17, 2013 11:50 AM

Cowan said:

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

pleasant understanding yet.

# January 17, 2013 7:04 PM

Grider said:

Very descriptive blog, I enjoyed that a lot. Will there be a part 2?

# January 17, 2013 11:10 PM

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

# January 19, 2013 3:49 AM

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

# January 20, 2013 1:46 AM

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.

# January 20, 2013 4:56 PM

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

# January 21, 2013 5:47 PM

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.

# January 22, 2013 1:14 AM

Patino said:

I was able to find good info from your content.

# January 22, 2013 5:59 AM

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!

# January 22, 2013 7:38 PM

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!

# January 23, 2013 8:24 PM

Rhyne said:

This is my first time pay a visit at here and i am actually impressed to read everthing at alone place.

# January 23, 2013 9:52 PM

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.

# January 25, 2013 1:23 PM

Crews said:

It's great that you are getting ideas from this post as well as from our argument made at this place.

# January 26, 2013 6:21 AM

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.

# January 27, 2013 1:38 AM

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

# January 28, 2013 9:53 PM

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!!

# January 28, 2013 11:56 PM

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.

# February 1, 2013 1:40 AM

Hobson said:

WOW just what I was looking for. Came here by searching for .

NET

# February 2, 2013 11:43 AM

Ng said:

I read this article fully regarding the comparison of most up-to-date and earlier

technologies, it's amazing article.

# February 3, 2013 9:40 AM

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

# February 3, 2013 10:54 AM

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!

# February 3, 2013 8:27 PM