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

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

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);


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

No comments: