Ajax-enabled WCF services and loadbalancing

by DotNetNerd 10. June 2010 20:35

This week I ran into a problem when we were deploying a webapplication that uses ajax-enabled webservices to an environment that uses loadbalancing. The services were running fine in the stage environment and when each of the servers were called directly, but as soon as we went through the loadbalancer they failed.

I started by checking if the svc files could be reached, and surely enough they could be accessed from the servers, but through the loadbalanced domain I got a 404.

Reading blogposts on the subject provided little help – well actually it just hightened my degree of confusion. So after some time I started thinking about IIS bindings. I remembered that I had written a custom WebScriptServiceHostFactory because we had several bindings which IIS doesn’t handle too well.

using System;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace MySite.ScriptingService
    public class MyCustomHostFactory : WebScriptServiceHostFactory
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
            //This makes it possible to control which binding is used by sorting them in IIS.
            return new ServiceHost(serviceType, baseAddresses[int.Parse(ConfigurationManager.AppSettings["BindingIndex"] ?? "0")]);

I started playing around with which binding we used, and as I suspected if the binding was not the one for the loadbalanced domain it returned the 404. This was one of those “doh!” moments. I still had a problem though, because the site could be accessed both with and without the www subdomain. A colleague pointed to the fact that we could use the URL rewrite plugin for IIS, and have it ensure all traffic was directed through one of the domains. As it turnes out it actually has a CanonicalHostNameRule that does just this because its a SEO good practice. Only issue I had left was that umbraco on the other hand has a practice that it must be accessed directly on one server, so changes are made on the master and replicated to the slave(s). This just required extending the conditions so it does not redirect if the umbraco folder is part of the path.

IIS routing

So now by posting this I hope Ill save someone else from getting a few extra gray hairs, and if not maybe I’ll save my self some other time when I can’t remember how I did…

Tags: , ,

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List