Click here to Skip to main content
15,867,860 members
Articles / Programming Languages / C#
Technical Blog

REST with WCF and Entity Framework with JSON Serialization

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
12 Apr 2013CPOL 16.8K   7  
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)


Written By
Technical Lead Plumsail
Russian Federation Russian Federation
Expert in SharePoint
The leader of SharePoint Forms Designer Team: http://spform.com
Co-founder of Plumsail: http://plumsail.com
My blog: http://formsdesigner.blogspot.com

Comments and Discussions

 
-- There are no messages in this forum --