I\'m trying to understand how to use WCF Data Services (based on EF 4.1) to create a restful web service that will persist entities passed as JSON objects.
I\'ve bee
Add parameters to your method. You'll also want some additional attributes on your WebInvoke.
Here's an example (from memory so it might be a little off)
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "modifyMyPerson")]
public void Modify(Person person) {
...
}
With person class something like this:
[DataContract]
public class Person {
[DataMember(Order = 0)]
public string FirstName { get; set; }
}
And json sent like this
var person = {FirstName: "Anthony"};
var jsonString = JSON.stringify({person: person});
// Then send this string in post using whatever, I personally use jQuery
EDIT: This is using "wrapped" approach. Without wrapped approach you would take out the BodyStyle = ...
and to stringify the JSON you would just do JSON.stringify(person)
. I just usually use the wrapped methodology in case I ever need to add additional parameters.
EDIT For full code sample
Global.asax
using System;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Routing;
namespace MyNamespace
{
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("myservice", new WebServiceHostFactory(), typeof(MyService)));
}
}
}
Service.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace MyNamespace
{
[ServiceContract]
[ServiceBehavior(MaxItemsInObjectGraph = int.MaxValue)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService
{
[OperationContract]
[WebInvoke(UriTemplate = "addObject", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void AddObject(MyObject myObject)
{
// ...
}
[OperationContract]
[WebInvoke(UriTemplate = "updateObject", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void UpdateObject(MyObject myObject)
{
// ...
}
[OperationContract]
[WebInvoke(UriTemplate = "deleteObject", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void DeleteObject(Guid myObjectId)
{
// ...
}
}
}
And add this to Web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>