I can't believe how long this took to figure out, I think I read every WCF tutorial out there, and now I look at it it's so mind bogglingly simple I don't know what I wasted my time doing! All I wanted was a WCF service that would accept a POST from jQuery with some JSON parameters and return some HTML, but it seems I repeatedly cocked up the JSON string format and the attributes for the contract. Anyway, here's a simple example so you don't have to endure my frustration. I used .NET 4.0 because it's .svc free.
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFrameworkMoniker=".NETFramework,Version=v4.0" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<serviceActivations>
<add relativeAddress="Service" service="Service" />
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service name="Service">
<endpoint behaviorConfiguration="webHttpBehaviour" binding="webHttpBinding" contract="Service" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Service
using System.IO;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
[ServiceContract, AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract, WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
public Stream Post(string message, int x, int y)
{
return new MemoryStream(Encoding.UTF8.GetBytes("<b>" + message + (x + y) + "</b>"));
}
}
jQuery
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-nightly.min.js"></script>
<script type="text/javascript">
$.ajax({
url: "service/post",
type: "POST",
contentType: "application/json",
data: '{"x":"1","y":"2","message":"The answer is: "}',
dataType: "html",
success: function(data) { $('body').html(data); }
});
</script>
</head>
<body>
</body>
</html>