Calling Service Operations Using POST

As you may know, OData enables you to define service operations that can be invoked by using either GET or POST requests. The topic Service Operations (WCF Data Services) shows how to define both kinds of service operations using WCF Data Services. Consider the following POST service operation that returns customer names as a collection of strings:

[WebInvoke(Method = "POST")]
public IEnumerable<string> GetCustomerNames()
{
// Get the ObjectContext that is the data source for the service.
NorthwindEntities context = this.CurrentDataSource;

    var customers = from cust in context.Customers
orderby cust.ContactName
select cust;

    foreach (Customer cust in customers)
{
yield return cust.ContactName;
}
}

As we mention in the topic Calling Service Operations (WCF Data Services), you can’t use the WCF Data Service client methods to access such an endpoint because POST requests are only sent by the client library when saving changes. This means that we need to use another web client API to call this service operation and manually consume the response in our application.

The following example uses HttpWebRequest/HttpWebResponse to call the GetCustomerNames service operation using a POST request and XDocument to access elements in the response document:

HttpWebRequest req =
(HttpWebRequest)WebRequest
.Create("https://myservice/Northwind.svc/GetCustomerNames");

// Use a POST to call this service operation.
req.Method = "POST";

// We need to set to this zero to let the service know
// that we aren't including any data in the POST.
req.ContentLength = 0;

using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
// Load the response into an XDocument.
XDocument doc = XDocument.Load(resp.GetResponseStream());

    // Get each child 'element' in the root 'GetCustomerNames' element,
// which contains the returned names.
foreach (XElement name in doc.Root.Descendants())
{
Console.WriteLine(name.Value);
}
}

Cheers!

Glenn Gailey