This is a code overview for creating a WPF endpoint that sends and receives JSON data.
Assemblies references
System.ServiceModel
System.Runtime.Serialization
System.ServiceModel.Web
Configure the endpoint
You can configure in the web.config your service endpoing by doing the following:
<system.serviceModel>
<services>
<service name="Listmill.Hub.WebDaemon.IISAdminEndpoint">
<endpoint address="http://localhost:8000/myservice/" binding="webHttpBinding" contract="Listmill.Hub.WebDaemon.IIISAdminEndpoint" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Alternatively, you can programmatical set up your endpoint by doing the following:
var port = 8000;
var address = string.Format("http://localhost:{0}/Supervisor", port);
var binding = new WebHttpBinding();
var host = new ServiceHost(this);
var endpoint = host.AddServiceEndpoint(typeof(ISupervisorEndpoint), binding, address);
endpoint.EndpointBehaviors.Add(new WebHttpBehavior());
host.Open();
Creating the Service Contract
You can create your contact in the traditional way. The implementation will require the use of WebInvoke attribute on the methods.
[ServiceContract(Namespace = "http://Listmill.Hub.WebDaemon")]
public interface IIISAdminEndpoint
{
int AddSite(string sitekey);
}
public class IISAdminEndpoint : IIISAdminEndpoint
{
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public int AddSite(string sitekey)
{
// do some stuff
}
}
Making Requests
You can make a request to the service using a traditional HttpWebRequest. Serialize an object to a JSON string using JavaScriptSerializer and pass the string as the POST data to your request.
// create your request and serialize an object into the request
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new { sitekey = site.SiteKey });
var jsonBytes = Encoding.UTF8.GetBytes(json);
var requestUrl = string.Format("http://{0}:{1}/iisadmin/addsite", webserver.IPAddress, 8000);
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentLength = jsonBytes.Length;
request.ContentType = "application/json";
using (var stream = request.GetRequestStream())
{
stream.Write(jsonBytes, 0, jsonBytes.Length);
}
// handle the response
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var streamReader = new StreamReader(responseStream))
{
var result = streamReader.ReadToEnd();
// do something with the result
}