среда, 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:
    <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
  <service name="[Name of your service]">
    <endpoint address="" behaviorConfiguration="restBehavior" binding="webHttpBinding" bindingConfiguration="crossDomain" contract="[Name of your contract]">
        <dns value="localhost" />
    <behavior name="restBehavior">
      <webHttp />

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" />

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:
public interface IService1
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);

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

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