I'm trying to write a simple REST service that I can talk to through my C# application. I want to send the REST service a JSON string and for it to send me a JSON string back. I want to do this using POST not GET as there is a fair amount of data that needs to be sent to it.. Also I would like to do it using what is built into the .net library that I'm using - .NET Framework 4.0.
So far I have the following code:
Client
public void SendJSONPostRequest(string sFunction, string sJSON)
{
string sRequest = FormRequest(m_sWebServiceURL, sFunction, string.Empty);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sRequest);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(sJSON);
request.ContentLength = byteArray.Length;
request.ContentType = @"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
public static string FormRequest(string sURL, string sFunction, string sParam)
{
StringBuilder sbRequest = new StringBuilder();
sbRequest.Append(sURL);
if (!sURL.EndsWith("/"))
{
sbRequest.Append("/");
}
sbRequest.Append(sFunction);
if ((!sFunction.EndsWith("/") &&
(!string.IsNullOrEmpty(sParam))))
{
sbRequest.Append("/");
}
sbRequest.Append(sParam);
return sbRequest.ToString();
}
Server
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.IO;
namespace ExampleRESTService
{
[ServiceContract(Name = "RESTServices")]
public interface IRESTServices
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = Routing.Route, BodyStyle = WebMessageBodyStyle.Bare)]
string GetCounts();
}
public static class Routing
{
public const string Route = "/GetCounts";
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RESTServices : IRESTServices
{
public string GetCounts()
{
string sData = "Hello"
return sData;
}
}
}
Now this isn't all of the code but it is the bits that are important I think. Also I've changed names for display online but it all compiles so please ignore if a typo. Apologies if there is something significant.
The REST service can be called from my client fine as is but my question is...
How do I extract the data in my REST service GetCounts() method that was posted to it from the client, i.e the JSON string?
Thanks in advance.