Adding a UserAgent to WCF Clients

Thursday, July 22, 2010 / Posted by Luke Puplett /

A quick post to show how to add a UserAgent to a WCF call so that it can be inspected on the server side, perhaps to see which versions of clients are calling your service.

And completely free of charge, I'm including some extraneous code I use to show how service method calls can be made without having to jump through hoops every time.

The code

        public T CallServiceMethod<T>(Func<T> methodCall, bool canExpectNull)
        {             
            T response;

            using (OperationContextScope scope = new OperationContextScope(this.ServiceClientChannel))
            {                 
                HttpRequestMessageProperty p = new HttpRequestMessageProperty();
 
                p.Headers.Add(System.Net.HttpRequestHeader.Cookie, this.AuthenticationCookie);
 
                p.Headers.Add(System.Net.HttpRequestHeader.UserAgent, typeof(ServiceHelper).Assembly.FullName);
 
                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, p);

                this.IncrementCallsInProgress();
                try
                {
                    response = methodCall.Invoke();

The blurb

I'm sorry about the broken lines - I so nearly picked a full width Blogger template, too. The method above essentially wraps a delegate invocation in some calls into WCF's OperationContext which adds the headers. It's interesting to look at the OperationContext in the debugger, much as you probably did with the HttpContext when first looking at an ASP.NET app - its sort of the equivalent but in reverse.

The method's ending isn't shown, I'm lazy like that, but it just catches errors, the finally block decrements the calls-in-progress counter and there's some logging.

On the server, I use the HttpContext.Current.Request.UserAgent string to log which client versions my customers are running. Useful.

Notice that I'm also adding a cookie which I store in the class that this method is part of. I'm using the built-in AuthenticationService which uses Forms Authentication and thus, cookies. This is not required in Silverlight as the IE stakc stores and reapplies appends any cookies received, automatically.

To use this method, I instantiate my service client proxy and then call ServiceHelper.CallServiceMethod( () => { return proxy.SomeMethod(xyz); });

The proxy call is thus invoked within the context changes above.

Labels: , , ,

0 comments:

Post a Comment