Creating a custom WCF REST service for SharePoint 2013
- System.Runtime.Serialization
- System.ServiceModel
- System.ServiceModel.Web
- sn -T MyRestService.dll
1
| <%@ ServiceHost Language= "C#" Debug= "true" Service= "{NameSpace}.{ServiceName}, {AssemblyName}, Version=1.0.0.0, Culture=Neutral, PublicKeyToken={PublicKeyToken}" CodeBehind= "Service1.svc.cs" %> |
- Replace the tokens here, represented by {Token} with the appropriate values for your project. e.g.,
- Deploy your solution
- Verify the service loads
- Note: see below for troubleshooting a common error.
- Add a HelloWorld operation to your contract, IService1.cs that is set up for REST.
- Implement the operation in Service1.svc.cs
- Update web.config with the appropriate info for your service
1
| <%@ ServiceHost Language= "C#" Debug= "true" Service= "MyRestService.Service1, MyRestService, Version=1.0.0.0, Culture=Neutral, PublicKeyToken={PublicKeyToken}" CodeBehind= "Service1.svc.cs" %> |
1
2
3
| [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "HelloWorld" ) string HelloWorld(); |
public string HelloWorld() { return "Hello World" ; } |
<behaviors> <serviceBehaviors> <behavior name= "Service1ServiceBehavior" > <serviceMetadata httpGetEnabled= "true" httpsGetEnabled= "true" /> <serviceDebug includeExceptionDetailInFaults= "true" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name= "jsonBehavior" > <webHttp /> </behavior </endpointBehaviors> </behaviors> <services> <service name= "MyRestService.Service1" behaviorConfiguration= "Service1ServiceBehavior" > <endpoint address= "" binding= "webHttpBinding" behaviorConfiguration= "jsonBehavior" contract= "MyRestService.IService1" /> <endpoint address= "mex" binding= "mexHttpBinding" contract= "IMetadataExchange" /> </service> </services> |
- Test your HelloWorld operation and you should see the following:
Troubleshooting
- If you get an error that says "This collection already contains an address with scheme http. There can be at most one address per scheme in this collection." this is due to having multiple bindings in IIS, which is common in SharePoint when you have multiple Alternate Access Mappings.
- In web.config, add the multiplesitebindingsenabled attribute to the servicehostingenvironment element.
<servicehostingenvironment aspnetcompatibilityenabled= "true" multiplesitebindingsenabled= "true" %></servicehostingenvironment%>
Reference:
|