Friday, January 6, 2017

WCF Configuration for Response in JSON Format

Below is a simple example of WCF that returns data in JSON format.

  • When using UriTemplate in WebInvoke attribute, all parameters should be of string type.
  • In the web.config, don't forget to add serviceBehavior and endpointBehavior. 
  • The endpointBehavior needs to have <webHttp /> and not <enableWebScript />.
  • When using WCF for Ajax client (i.e., $.ajax()), keep in mind that Ajax client only knows "GET" and "POST" and not "PUT" or "DELETE".

IService2.cs
[OperationContract]
[WebInvoke(Method ="GET", 
   UriTemplate = "/CategoryName/{id}", 
   ResponseFormat = WebMessageFormat.Json, 
   RequestFormat =WebMessageFormat.Json)]
string GetCategoryName(string id);

Service2.svc.cs
public class Service2 : IService2
  public string GetCategoryName(string id)
  {
     string retVal = "NotFound";
     int categoryID = Convert.ToInt32(id);
     using (NorthwindEntities db = new NorthwindEntities())
     {                
        var category = db.Categories.Find(categoryID);
        if(category != null)
        {
           retVal = category.CategoryName;
        }
     }
     return string.Format("Category with ID {0} is {1}.", categoryID, retVal);
   }
}

web.config

<system .servicemodel="">
    <behaviors>
      <servicebehaviors>
        <behavior name="default">
          <servicemetadata httpgetenabled="true" httpsgetenabled="true">          
          <servicedebug includeexceptiondetailinfaults="false">
        </servicedebug></servicemetadata></behavior>
      </servicebehaviors>
      <endpointbehaviors>
        <behavior name="default">
          <webHttp/>
        </behavior>
      </endpointbehaviors>
    </behaviors>
    <services>
      <service behaviorconfiguration="default" name="NorthwindWCF.Service2">
        <host>
          <baseaddresses>
            <add baseaddress="http://localhost:4957">
          </add></baseaddresses>
        </host>
        <endpoint behaviorconfiguration="default" binding="webHttpBinding" contract="NorthwindWCF.IService2">
        </endpoint>
      </service>
    </services>
    <protocolmapping>
      <add binding="basicHttpsBinding" scheme="https">
    </add></protocolmapping>
    <servicehostingenvironment aspnetcompatibilityenabled="true" multiplesitebindingsenabled="true">
  </servicehostingenvironment></system>

No comments: