Mar 25, 2010

Host WCF Services in SharePoint 2010

As a completion of my post, how to Host WCF Data Service in SharePoint 2010  I am here to show how to host WCF services and WCF RESTful services inside SharePonit 2010.

Create a empty SharePoint project and add an ISAPI mapped folder

Add "new item" and select "WCF Service"
when creating WCF service inside a SharePoint Project, you won't get .svc file, only one interface and one class file:
  • Add this attribute to implemntation class:
    • [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
  • specify Namespace in the interface, otherwise your proxy script class will get a namespace like org.ui
    • [ServiceContract(Namespace="")]
Create a service.svc file under ISAPI folder
  • As it is hosted in SharePoint, we have to use non-configuation approach (Factory) to define endpoint (see here for details). In other word, no web.config modification, in stead use Factory in .svc file as follows:
  • <%@ServiceHost Language="C#" Debug="true" Service="SharePointHostWCF.WCFService, SharePointHostWCF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d82e2e229c90dd3e" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"% >
  • WebScriptServiceHostFactory will define a endpoint callable from Javascript.
create a sharepoint ajax enabled application page to test your WCF service
  • see my other post on how to make ajax enabled sharepoint page;
  • use asp:servicereference to load a service proxy class in runtime;
  • in javascript,you should be able to get a IWCFService object and use it to call service methods;
  • you can't call it from another iis web application, since it is treated as a cross site scripting (CSS);

What if you want to implement a RESTful Service?
  • add this attribute to interface method:
    • [WebGet(UriTemplate = "Hello", ResponseFormat = WebMessageFormat.Xml)]
  • change Factory in service.svc to WebServiceHostFactory. otherwise you get the following errors:
  •   Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'.
  • you can now test service from browser in a RESTful way;
  • if you choose Json for ResponseFormat instead, browser won;t be able to display, instead asking you to download. You should test it in Fiddler;
  • still want to consume this RESTful service from script, see my other post for detail;