How Deploy a WCF Service To SharePoint 2010

Update 29 September 2010 – I’ve created a Visual Studio project item that allows WCF services to be easily added to SharePoint. Rather then start my own Codeplex project , I’ve contributed my addition to http://cksdev.codeplex.com. CKS:Dev is an excellent collection of useful tools and utilities that makes developing for SharePoint using Visual Studio 2010 much easier. Download it now, trust me, it’s well worth the effort.

The new packaging and deployment stuff for SharePoint 2010 is certainly a lot better than VSeWSS but there are a few things missing, such as the ability to add a WCF service as a project item. One of these days I’ll build a template to do it but for now here’s a quick step by step guide.

Add SVC file to Layouts folder

To make a Windows Communication Framework service available we need to host it somewhere. Since SharePoint runs on IIS, we need to create a .svc file with details of the service implementation. Of course before we create the file we need somewhere to put it and for the purposes of this demonstration we’ll use a custom subfolder within the %sproot%\TEMPLATE\Layouts folder. We can set up this folder automatically using our Visual Studio project.

  1. From the Project menu select Add SharePoint “Layouts” Mapped Folder. You’ll notice that a new folder is added to the solution.
  2. We can now go ahead and add our MyWCFService.svc file. In the Layouts\<MyProjectName> folder. Add a new XML File named MyWCFService.svc.
  3. Replace the contents of the file with the following code:
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$"%>
<% @ServiceHost Service="MyProject.MyService" %>

Token Replacement in Visual Studio

Visual Studio 2010 allows the use of replaceable tokens when creating SharePoint solution packages. Our .svc file makes use of the token $SharePoint.Project.AssemblyFullName$ that will be replaced when the package is built, by the 4 part assembly name for the associated assembly. However, tokens are not automatically replaced in files with an .svc extension. Thankfully this is a simple problem to resolve.

  1. Navigate to C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools
  2. Open the Microsoft.VisualStudio.SharePoint.targets file. You’ll find that this is an Xml format file that defines various configuration settings for building SharePoint projects.
  3. Find the TokenReplacementFileExtensions element and append svc to the list of file extensions as shown:
<TokenReplacementFileExtensions>$(TokenReplacementFileExtensions);xml;aspx;ascx;webpart;dwp;svc </TokenReplacementFileExtensions>

Adding WCF service configuration to SharePoint

As well as an .svc file, IIS also needs to reads the configuration of the WCF service from the web.config file. For the purposes of this quick how-to we’ll make the necessary changes manually.

  1. Open the web.config file for our application (this will be found at C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config if the application is the first application running on port 80).
  2. In the system.serviceModel element add the following configuration details:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<bindings>
    <basicHttpBinding>
        <binding name="MyDemoBinding">
            <security mode="TransportCredentialOnly">
                <transport clientCredentialType="Ntlm" />
            </security>
        </binding>
    </basicHttpBinding>
</bindings>
<behaviors>
    <serviceBehaviors>
        <behavior name="MyDemoBehavior">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
    </serviceBehaviors>
</behaviors>
<services>
    <service behaviorConfiguration="MyDemoBehavior" name="MyProject.MyService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyDemoBinding" contract="MyProject.IMyService">
        <identity>
            <dns value="localhost" />
        </identity>
    </endpoint>
    <host>
        <baseAddresses>
            <add baseAddress=”http://localhost/_layouts/MyProjectName” />
        </baseAddresses>
    </host>
    </service>
</services>

Note: In an ideal world we’d add some code to our SharePoint solution that would automatically add the appropriate configuration details to the web.confg file but that’s a story for another day.

We’re now ready to deploy the service to SharePoint. From the Build menu select Deploy MyProject. Visual Studio will now build the solution, create a WSP package, and then deploy the package to our SharePoint server.

  • http://www.sharepointbits.com/ Chris Beckett

    FYI – SharePoint 2010 now includes Service Host Factories so you no longer need to generate and deploy your own endpoint configurations. I just put up a blog post on writing custom WCF services demonstrating how to do this.

    http://www.sharepointbits.com/…/…sharepoint-2010.html

  • http://www.chaholl.com/Default.aspx chaholl

    Thanks for that Chris, I read through your post and it does a good job of explaining service host factories.

  • nvjdnkll

    According to MSDN, for deploying custom web service, we need to create *wsdl.aspx and *disco.aspx files, and put them with .asmx together under _vti_bin folder (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi). And put the dll under bin folder of the root of sharepoint virtual directory. It works correctly for me.

  • http://kwizcom.blogspot.com/ Shai

    Editing visual studio files to add more file ext. to replace tokens?

    Bad idea!

    say you get latest version of project to another machine, and build it – you will get no build errors and the tokens will not be replaced. very hard to find. also when another developer wants to get latest version and build it… this is very scary advice that should be taken seriously.

    But – nice to know where it is!

  • http://www.chaholl.com/Default.aspx chaholl

    Fair point. Maybe editing the targets file has it’s drawbacks! I wrote thie post on SP2010 Beta and was kinda hoping that the RTM would ship with svc in the targets file by default, thus removing the need for any of this.

    A better way to achieve the same result is to update the project file and add the additional extension there:

    ie.

    <PropertyGroup>
    <TokenReplacementFileExtensions>svc</TokenReplacementFileExtensions>
    </PropertyGroup>

    Or better still. Get the latest version of CKSDev and use the template in there which will do all of this good stuff for you!

  • http://blogs.breezetraining.com.au/mickb Mick Badran

    Hi – you might want to keep msdn.microsoft.com/en-us/library/ff521581.aspx

    handy as it is pretty much the same example as what you’ve done except with all the recommendations in one concise example.

    It also (which something I couldn’t see in your sample) adds a reference to Microsoft.SharePoint.Client.ServerRuntime.dll – which gives you your current context in your service. i.e. SPContext.Current – actually works.

    Nice sample though – well done.

  • Daniel Roger

    Thanks, great post. And you might want to keep http://mosshosting.asphostportal.com/?p=321. It talk about customize WCF in sharepoint 2010.

  • http://lgp1985.wordpress.com/ Luis Gustavo

    Great tips, but is there any way to make it work with streams bigger than 64kb, or transactions?

  • http://www.chaholl.com/archive/2011/08/31/sharepoint-2010-search-via-rest.aspx Charlie Holland » Blog Archive » SharePoint 2010: Search via REST – Freelance SharePoint Consultant, Author and Trainer

    [...] I covered this some time ago in this post. However, rather than take all these steps manually, I highly recommend installing the CKSDev extension for Visual Studio. The rest of this post will assume that you have it installed. [...]

  • http://blog.repsaj.nl/?p=450 SharePoint 2010: deploying webservice to single webapplication | Jaspers' Weblog

    [...] [...]