среда, 15 февраля 2012 г.

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, lets define configuration for this service:
<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":
<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:
[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:
$.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:
public string GetOrder(Int32 id)
{
    
// getting order…
    return SerializeJSON(order);
}

static string SerializeJSON<T>(T obj)
{
    JavaScriptSerializer serializer = 
new JavaScriptSerializer();
    
return serializer.Serialize(obj);
}

Комментариев нет:

Отправить комментарий