Connect To WCF Web Service From SharePoint Hosted Add-In

Here are the steps to connect to WCF Web Service from SharePoint Hosted Add-in.

  1. Create WCF Web Service using the template available in Visual Studio.
  2. In Controller class, write the below interface.
    1. [OperationContract]  
    2. [WebGet(ResponseFormat = WebMessageFormat.Json,  
    3. UriTemplate = "SaveDocument?url={docUrl}")]  
    4. byte[] SaveDocument(string docUrl);  
  3. Create a method in code behind file, as shown below.
    1. public byte[] SaveDocument(string docUrl)  
    2. {  
    3.    //Write your own code here and return byte[]  
    4. }  
    Note

    Return type should be same as declared in interface. Here, “SaveDocument” method will be called on accessing the Web Service with this URL -

    http://localhost/IISFolder/Controller.svc/SaveDocument?url=" + "urlParameter";

  4. Call Web Service from SharePoint Hosted Add-in using function.
    1. function test() {  
    2.     //web service URL with parameter  
    3.     var requestUriTest = "http://localhost/IISFolder/Controller.svc/SaveDocument?url=" + "urlParameter";  
    4.     $.support.cors = true;  
    5.     return $.ajax({  
    6.         url: requestUriTest,  
    7.         type: "GET",  
    8.         data: "",  
    9.         headers: {  
    10.             "accept""application/json;odata=verbose"  
    11.         },  
    12.         ContentType: "application/json; charset=utf-8",  
    13.         dataType: "json",  
    14.         success: function(data) {  
    15.             //Process the data  
    16.         },  
    17.         error: function(data) {  
    18.             //Alert error  
    19.             alert(data);  
    20.         }  
    21.     });  
    22. }  
Next Recommended Reading Web API Self-Hosting