Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint

SharePoint: Getting This collection already contains an address with scheme HTTP error when creating a custom WCF Service

0.00/5 (No votes)
14 Aug 2013CPOL 6.3K  
Getting This collection already contains an address with scheme HTTP error when creating a custom WCF Service.

Problem

The problem is caused by the fact that IIS supports specifying multiple IIS bindings per site (which results in multiple base addresses per scheme, in our case HTTP), but a WCF service hosted under a site allows binding to only one base address per scheme.

Multiple addresses example (in our case two):

clip_image002

Solution

Create a custom service factory to intercept and remove the additional unwanted base addresses that IIS was providing.

A) Add the custom service factory to your Custom.svc file:

XML
<%@ServiceHost language=c# Debug="true" 
  Service="MySolution.Services.CustomService, $SharePoint.Project.AssemblyFullName$"
  Factory="MySolution.Core.CustomHostFactory", $SharePoint.Project.AssemblyFullName$ %>

* Don’t forget to add the assembly full name: $SharePoint.Project.AssemblyFullName$ or you’ll get “The CLR Type 'typeName' could not be loaded during service compilation” error.

B) Create a custom factory by inheriting from ServiceHostFactory and overriding the CreateServiceHost method.

By using the current request host name, you can check which base address to use, and if no host name found, use the first one.

C#
public class CustomServiceHostFactory : ServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            string hostName = HttpContext.Current.Request.Url.Host;
            foreach (Uri uri in baseAddresses)
            {
                if (uri.Host == hostName)
                    return new ServiceHost(serviceType, uri);
            }
            return new ServiceHost(serviceType, baseAddresses[0]);
        }
    }

    public class CustomHost : ServiceHost
    {
        public CustomHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        { }
        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();
        }
    }
}

Hope you’ll find this post helpful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)