Recently, I had been working on how to get a WCF service hosted in SharePoint. The requirement was to host a WCF service in SharePoint and a custom webpart would access the service. So in this post, I will illustrate how to host WCF in SharePoint.
Environment:
- Microsoft SharePoint Server 2007
- Visual Studio 2008
- Visual Studio Extensions for WSS 3.0 v1.3 March CTP
1) First let’s create a WCF service and its implementation. For this, create a project of type WCF Service Library. Name it SPService. This will create a default interface “IService.cs” and its implementation “Service.cs”.
2) Delete the defaut IService.cs and Service.cs files.
3) Add a new item of type WCF Service named SPService.
4) Modify the ISPService interface as shown below.
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace SPService
{
// NOTE: If you change the interface name "ISPService" here, you must also update the reference to "ISPService" in App.config.
[ServiceContract]
public interface ISPService
{
[OperationContract]
string SayHello(string name);
}
}
5) Modify SPService class as shown below.
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
namespace SPService
{
// NOTE: If you change the class name "SPService" here, you must also update the reference to "SPService" in App.config.
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class SPService : ISPService
{
#region ISPService Members
public string SayHello(string name)
{
return string.Concat("Hello ",name);
}
#endregion
}
}
6) Modify the web.config file as shown below.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <compilation debug="true" /> </system.web> <!-- When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries. --> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicBinding"> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Ntlm" /> </security> </binding> </basicHttpBinding> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> <services> <service behaviorConfiguration="NewBehavior" name="SPService.SPService"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicBinding" name="basicBindingEndPoint" contract="SPService.ISPService" /> <!--<host> <baseAddresses> <add baseAddress="http://localhost:8080/SPService" /> </baseAddresses> </host>--> </service> </services> <behaviors> <serviceBehaviors> <behavior name="NewBehavior"> <serviceDebug /> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
7) Sign the project .
8) Now run the project. This will bring up the WCF Test Client wizard. Test remote method by invoking the method. It should respond you as shown below.
9) Now create a SharePoint project of template type Empty. Name it “SharePoint.WSP”. Select the option to Deploy it to GAC.
10) Create the folders “RootFiles”, “ISAPI”, “SPService” in the structure as shown below. We will host the service in the folder “SPService”.
11) Rename the “App.config” file in project SPService to “web.config”. Now in project, SharePoint.WSP, select the folder SPService and select to add an existing item. Navigate to web.config file and add it as a link.
12) Similarly, add a link to assembly SPService.dll also.
13) Then in folder SPService, add an item of type “SPService.svc”. Modify the file to following.
<%@ Assembly Name="SPService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ee2ed923e46a9fcd" %> <%@ ServiceHost Service="SPService.SPService,SPService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ee2ed923e46a9fcd" %>
You can retrieve the full assembly signature using a reflector.
14) Go to the WSP view (View – > Other Windows -> WSP View). The manifest.xml file should look like below.
15) Now set site url in the properties of project SharePoint.WSP where the solution will be deployed. Then deploy the solution.
16) Now try to access the service with the url http://sandeep-pc/_vti_bin/spservice/spservice.svc . At this point you may receive an VirtualPath error like below.
Exception: System.ArgumentException: virtualPath
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.IsExcludedPath(String virtualPath)
at Microsoft.SharePoint.ApplicationRuntime.SPVirtualPathProvider.FileExists(String virtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
at System.ServiceModel.Activation.HttpHandler.ProcessRequest(HttpContext context)
The problem here is that SPVirtualPathProvider isn’t coded to handle URLs that start with ‘~’;
See workaround references for this:
- http://blah.winsmarts.com/2008-5-SharePoint_2007_as_a_WCF_host_-_Step_-4,_Write_a_Virtual_Path_Provider.aspx
- http://blogs.msdn.com/gzunino/archive/2007/09/17/hosting-a-wcf-service-in-windows-sharepoint-services-v3-0.aspx
17) As a workaround, follow the procedure below.
18) Add a folder named WCFSupport, in the project SharePoint.WSP. In this folder, add a new class file named “WCFVirtualPathProvider” and add the following lines of code.
class WCFVirtualPathProvider : VirtualPathProvider
{
public override string CombineVirtualPaths(string basePath, string relativePath)
{
return Previous.CombineVirtualPaths(basePath, relativePath);
}
public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
{
return Previous.CreateObjRef(requestedType);
}
public override bool DirectoryExists(string virtualDir)
{
return Previous.DirectoryExists(virtualDir);
}
public override bool FileExists(string virtualPath)
{
// Patches requests to WCF services: That is a virtual path ending with ".svc"
string patchedVirtualPath = virtualPath;
if (virtualPath.StartsWith("~", StringComparison.Ordinal) &&
virtualPath.EndsWith(".svc", StringComparison.InvariantCultureIgnoreCase))
{
patchedVirtualPath = virtualPath.Remove(0, 1);
}
return Previous.FileExists(patchedVirtualPath);
}
public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath,
System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
{
return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
public override string GetCacheKey(string virtualPath)
{
return Previous.GetCacheKey(virtualPath);
}
public override VirtualDirectory GetDirectory(string virtualDir)
{
return Previous.GetDirectory(virtualDir);
}
public override VirtualFile GetFile(string virtualPath)
{
return Previous.GetFile(virtualPath);
}
public override string GetFileHash(string virtualPath, System.Collections.IEnumerable virtualPathDependencies)
{
return Previous.GetFileHash(virtualPath, virtualPathDependencies);
}
protected override void Initialize()
{
base.Initialize();
}
}
19) Create another class file named “WCFVPPRegModule” and add the following lines of code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Hosting;
namespace SharePoint.WSP.WCFSupport
{
class WCFVPPRegModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
// do nothing
}
public void Init(HttpApplication context)
{
if (!wcfProviderInitialized)
{
lock (locker)
{
WCFVirtualPathProvider wcfVPP = new WCFVirtualPathProvider();
HostingEnvironment.RegisterVirtualPathProvider(wcfVPP);
wcfProviderInitialized = true;
}
}
}
#endregion
static bool wcfProviderInitialized = false;
static object locker = new object();
}
}
20) Now after we have created the HttpModule, we need to register this in the web.config file of the root web application. This can be done manually or by creating a feature receiver which will apply the modification to the web.config file. I am going to use the later one. These feature receiver will be scoped at WebApplication and enabling this feature will apply the necessary modification to get the service running.
21) Add a new class file named “WCFSupportReceive.csr” in the folder “WCFSupport” and change it to below.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
namespace SharePoint.WSP.WCFSupport
{
[Guid("1860F007-6E2B-4a95-A8B6-371AB8F6B012")]
class WCFSupportReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
if (webApp != null)
{
foreach (ModificationEntry entry in Entries)
{
webApp.WebConfigModifications.Add(CreateModification(entry.Name, entry.XPath, entry.Value));
}
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
if (webApp != null)
{
foreach (ModificationEntry entry in Entries)
{
webApp.WebConfigModifications.Remove(CreateModification(entry.Name, entry.XPath, entry.Value));
}
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
}
public override void FeatureInstalled(SPFeatureReceiverProperties properties){}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties){}
private struct ModificationEntry
{
public string Name;
public string XPath;
public string Value;
public ModificationEntry(string Name, string XPath, string Value)
{
this.Name = Name;
this.XPath = XPath;
this.Value = Value;
}
}
private ModificationEntry[] Entries = {
new ModificationEntry(
"add[@name='WCFVPPRegModule']",
"configuration/system.web/httpModules",
@"<add name=""WCFVPPRegModule"" type=""SharePoint.WSP.WCFSupport.WCFVPPRegModule,SharePoint.WSP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1948038ea0d4e8e4"" />"
)
};
public SPWebConfigModification CreateModification(string Name, string XPath, string Value)
{
SPWebConfigModification modification = new SPWebConfigModification(Name, XPath);
modification.Owner = WebConfigModificationOwner;
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modification.Value = Value;
return modification;
}
private const string WebConfigModificationOwner = "SharePoint.WSP";
}
}
Note: The ModificationEntry[] is used to define the set of configurational changes needed to be made to web.config file. For now, we just need to register a http module, so there is just one entry defined. Use reflector to find the full signed signature of the assembly. Make sure that the PublicKeyToken matches to that of the assembly.
22) Then go to WSP View (View – > Other Windows-> WSP View). This is how it looks in WSP View.
23) Change the feature.xml of the WCFSupportReceiver as shown below.
<?xml version="1.0" encoding="utf-8"?> <Feature Id="1860f007-6e2b-4a95-a8b6-371ab8f6b012" Title="WCFSupportReceiver" Description="Enable WCFSupport for SPService" Scope="WebApplication" Version="1.0.0.0" Hidden="FALSE" ReceiverAssembly="SharePoint.WSP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1948038ea0d4e8e4" ReceiverClass="SharePoint.WSP.WCFSupport.WCFSupportReceiver" DefaultResourceFile="core" xmlns="http://schemas.microsoft.com/sharepoint/"> <ElementManifests /> </Feature>
The key things to note here are:
- The feature is scoped at WebApplication since we are making change in the web.config file of the web application. Also this means that in each web application, this feature has to be activated in order to acecess WCF Service.
- Use the reflector to get the full assembly signature for the ReceiverAssembly.
24) Now everything set, deploy the project. Go to “Manage Web Application Features” of the web application into which the solution was deployed. Activate the WCFSupportFeaure feature if it is not yet activated. You can also verify this by opening web.config file of web application and see for the entry for “WCFSupportReceiver”.
25) Navigate to the url again: http://sandeep-pc/_vti_bin/spservice/spservice.svc .You should see a response like below.
26) So the service has been hosted. To test the service, following the procedures below.
- Create a console application.
- Add the service reference to the above hosted service.
- Modify the client code to the following.
using System;
using System.Collections.Generic;
using System.Text;
namespace TestClient
{
class Program
{
static void Main(string[] args)
{
try
{
Service.SPServiceClient client = new TestClient.Service.SPServiceClient();
string response = client.SayHello("sandeep");
Console.WriteLine(string.Format("Response from server: {0}", response));
}
catch (Exception exc)
{
Console.WriteLine(string.Format("Error:{0}", exc.Message));
}
Console.ReadLine();
}
}
}
This is the output of the client application.
I would suggest you to have a look at the following references that I went through to get this done.
References:
- http://blah.winsmarts.com/2008-5-SharePoint_2007_as_a_WCF_host_-_Step_-1,_make_a_WCF_Home.aspx
- http://blah.winsmarts.com/2008-5-SharePoint_2007_as_a_WCF_host_-_Step_-4,_Write_a_Virtual_Path_Provider.aspx
- http://blah.winsmarts.com/2008-9-Getting_SPContextCurrent_in_a_SharePoint_2007_WCF_Service.aspx
- http://blogs.msdn.com/gzunino/archive/2007/09/17/hosting-a-wcf-service-in-windows-sharepoint-services-v3-0.aspx














I don’t know If I said it already but …Great site…keep up the good work.
I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. Thanks,
A definite great read..Jim Bean
Comment by JimmyBean — October 1, 2009 @ 3:48 PM
If anyone has a link to a similar procedure for Sharepoint 2010, please post it here. Would the WCF service be hosted as a Sandbox Solution, a Farm Solution, or a Feature? Thank you!
Comment by Eric Rangell — May 2, 2011 @ 1:33 PM
I found the answer in the book: Microsoft SharePoint 2010: Building Solutions for SharePoint 2010 (Books for Professionals by Professionals) by Sahil Malik. In Chapter 5 he walks through deployment of a WCF service in SP2010. The service is deployed to the GAC using the Advanced tab of the Package.
Comment by Eric Rangell — May 3, 2011 @ 5:24 PM