Creating a .NET WCF 4.0 JSON Service

I had a lot of trouble getting configuring a .NET 4.0 WCF service which could be called from an HTML page using JQUERY.  The issue was pretty much all with configuring the service and so I thought I would share the web.config that I finally got that allowed the service to work properly.

First, ensure your service methods are decorated as shown:

    [ServiceContract]

    public interface ICommonService

    {

        [OperationContract]

        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]

        string[] GetData(string id);

    }

 

Second, use this as a starting point for your web.config:

<?xml version="1.0"?>

<configuration>

  <system.web>

    <customErrors mode="Off" />

    <compilation debug="true" targetFramework="4.0" />

  </system.web>

 

  <system.serviceModel>

   

    <behaviors>

      <serviceBehaviors>

        <behavior>

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="true"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="MyServiceBehavior">

          <enableWebScript />

        </behavior>

      </endpointBehaviors>

    </behaviors>

   

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

   

    <services>

      <service name="MyJsonWcfService.Service1">

        <endpoint address="" behaviorConfiguration="MyServiceBehavior"

          binding="webHttpBinding" contract="MyJsonWcfService.IService1" >

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

      </service>

    </services>

   

  </system.serviceModel>

 

  <system.webServer>

    <directoryBrowse enabled="true"/>

  <modules runAllManagedModulesForAllRequests="true"/>

  </system.webServer>

 

</configuration>