Saturday, October 29, 2016

Sending POST call to WCF REST web method - SharePoint

When it comes to SharePoint usage there are many examples in the web about REST GET calls, but not so much on POST. So here goes..

My target REST method signature is as follows

public List<Details> GetDetails(string ids)

The method declaration in the Interface is as below:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "GetDetails", BodyStyle = WebMessageBodyStyle.Wrapped,
 RequestFormat = WebMessageFormat.Json,
 ResponseFormat = WebMessageFormat.Json)]
List<Details> GetDetails(string ids);

The trick here is making the web message body style "Wrapped"

Now from the client-side you make a call to the method.
In my example I use the service invocation within a AngularJS function. You send the parameter information in the data

    $scope.TestMethod = function () {
        var endpointAddress = "http://myTestSite.com/sites/TestSite/_vti_bin/CustomService.svc";
        var callurl = endpointAddress + "/GetDetails";
        $.ajax({
                type: "POST",
                url: callurl,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"ids": "18"}',
                success: function () {
                    alert('success');
                },
                error: function () {
    alert('error');
}
            });

    };

Friday, October 28, 2016

Passing parameter containing special characters to web service methods

Web service does not process parameters with special characters as those can be candidates to dangerous inputs.

So as a workaround you can send the parameters as a query string. That said, the query string should not be too long since there are limitations

For illustration purposes, in the below example JavaScript call I send two variables id & date as method parameters. The address information which is included in variable address1 & address2 are send as  query string.

var restUrl = _spPageContextInfo.webAbsoluteUrl +
            "/_vti_bin/MyService.svc/MyMethod/" + id + "/" + date + "?address1=" + encodeURIComponent(address1) + "&address2=" + encodeURIComponent(address2) ;

Inside your web method access the query string as below:

string address = HttpContext.Current.Request.QueryString["address1"];