Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

REST with WCF and Entity Framework with JSON Serialization

5.00/5 (7 votes)
12 Apr 2013CPOL 17K  
REST with WCF and Entity Framework with JSON serialization.

Problem: you have some database and use Entity Framework to get data from it. You need develop web-service which returns JSON-data based on your entities. And as a consumer of this service you need to use javascript client. Also, you should provide cross-domain access to your web-service.

First, let's define configuration for this service:

XML
<bindings>
  <webHttpBinding>
    <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
  </webHttpBinding>
</bindings>
<services>
  <service name="[Name of your service]">
    <endpoint address="" behaviorConfiguration="restBehavior" binding="webHttpBinding" 
              bindingConfiguration="crossDomain" contract="[Name of your contract]">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
  </service>
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="restBehavior">
      <webHttp />
    </behavior>
  </endpointBehaviors>
</behaviors>

Parameter crossDomainScriptAccessEnabled="true" allows requests from another domain. If you need to use SSL, just add security tag to the binding tag with mode="Transport":

XML
<binding name="crossDomain" crossDomainScriptAccessEnabled="true">
<security mode="Transport" /></binding>

Okey, now we should define service contract. To get JSON-data from your web-methods you should add WebGet(ResponseFormat = WebMessageFormat.Json) attribute to each web-method:

C#
[ServiceContract]public interface IService1
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string GetOrder(Int32 id);
}

Now, we can request our service something like this, I use jQuery:

JavaScript
$.getJSON('/GetOrder?id=7&callback=?'function (data) {
...
});

Great, but when we try to return entity we get this error:

The type 'xxx' cannot be serialized to JSON because its IsReference setting is 'True'.

Entity Framework doesn't support JSON-serialization, so I found this workaround:

C#
public string GetOrder(Int32 id)
{
    // getting order…
    return SerializeJSON(order);
}
static string SerializeJSON<T>(T obj)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Serialize(obj);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)