Here's a sample I put together that POSTs an entity to a WCF REST service (using jQuery on the client side). If you're not using jQuery, I think you'll still see how to handle it.
Here's the HTML & JavaScript:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
Name: <input type="text" id="name" /><br />
Desc: <input type="text" id="desc" /><br />
<button id="submit">Send!</button>
<script type="text/javascript">
$(function () {
$("#submit").click(function (e) {
e.preventDefault();
var theData = {};
theData["Name"] = $("#name").val();
theData["Desc"] = $("#desc").val();
$.ajax({
type: "POST",
url: "ProdService.svc/product/add",
data: JSON.stringify(theData),
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (e, t, x) {
alert(t);
}
});
});
});
</script>
</body>
</html>
The key things to note is that I'm setting the content type of the request to application/json
. That's key for WCF so it knows what's being sent up.
My service is defined as such:
[OperationContract]
[WebInvoke(Method="POST", ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,
BodyStyle=WebMessageBodyStyle.Bare, UriTemplate="product/add")]
String AddProduct(Product p)
{
return "Got " + p.Name;
}
And my entity is like this:
[DataContract]
public class Product
{
[DataMember()]
public String Name { get; set; }
[DataMember()]
public String Desc { get; set; }
}
My web.config is set up like this:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication2.ProdServiceAspNetAjaxBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication2.ProdService">
<endpoint address="" behaviorConfiguration="WebApplication2.ProdServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApplication2.ProdService" />
</service>
</services>
</system.serviceModel>
The key in the web.config is that my endpointBehavior
uses webHttp
instead of enableWebScript
. Other than that, this is pretty much an out-of-the-box configuration.
So the keys are that my payload is a JavaScript object literal converted to a JSON-ized string. My service is expecting the request format to be JSON, and since my Product
class is decorated with the DataMember
and DataContract
attributes, it can deserialize my payload to a Product
class instance.
I hope this helps. Please let me know if you have other questions and I'll update my answer accordingly.