How to Create WCF Application which accepts parameter in JSON format.

Below example and code shows How we can use WCF Service which accepts JSON as parameter inputs and performs insert operation with ADO.Net Entity Framework

In this sample example I am trying to add entry in StateMaster Table. For Insert operation StateMaster table required two parameters which is StateName and StateCode.

Below WCF Operation shows step by step process to create WCF Service and Databse insert operation.

Let’s begin with WCF Creation:

1.Create WCF Application from Visual Studio

I have created Application Named: WcfService

Visual Studio WCG Application

2. Now Create Method AddState in WCF interface

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Services;

namespace WcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMasterSVC" in both code and config file together.
    [ServiceContract]
    public interface IMasterSVC
    {      
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "AddState", BodyStyle = WebMessageBodyStyle.Wrapped)]
        [OperationContract]
        bool AddState(Stream strInput);
    }
}

[WebInvoke(Method = “POST”, RequestFormat = WebMessageFormat.Json, UriTemplate = “AddState”, BodyStyle = WebMessageBodyStyle.Wrapped)]

Here We can see that this Method is using POST and UriTemplate = “AddState”

3. Create Method in WCF Class file

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Text;
using System.Web.Script.Serialization;

namespace WcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MasterSVC" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select MasterSVC.svc or MasterSVC.svc.cs at the Solution Explorer and start debugging.
    public class MasterSVC : IMasterSVC
    {

        public bool AddState(Stream str)
        {
            bool result = false;

            try
            {
                if(str != null)
                {
                    //Get Parameter Key Value from JSON Formatted String 
                    string strJsonFormatString=  GetJSONPatameter(str);                                                            
                    
                    //Extract Paramter Value 
                    if (!string.IsNullOrEmpty(strJsonFormatString))
                    {
                        //Deseiralize JSON Format String Paramter from String
                        Dictionary<string, object> objJson = GetJSONObj(strJsonFormatString);

                        if (objJson != null)
                        {
                            string StateName = objJson["StateName"].ToString();
                            string StateCode = objJson["StateCode"].ToString();

                            BAL.ProjectEntitiesSQLConnStr context = new BAL.ProjectEntitiesSQLConnStr();

                            BAL.StateMaster objState = new BAL.StateMaster();

                            objState.StateCode = StateCode;
                            objState.StateName = StateName;

                            context.StateMasters.Add(objState);

                            context.SaveChanges();
                        }
                    }
                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;

                throw ex;               
            }

            return result;
        }

        #region "JSON Related Methods"
        private string GetJSONPatameter(Stream str)
        {
            StreamReader strReader = new StreamReader(str);

            string strJsonFormatString = strReader.ReadToEnd();

            int startIndex = strJsonFormatString.IndexOf("[");
            int endIndex = strJsonFormatString.IndexOf("]");
            int length = endIndex - (startIndex + 1);

            if (startIndex > 0)
            {
                strJsonFormatString = strJsonFormatString.Substring(startIndex + 1, length);
            }

            return strJsonFormatString;
        }

        public static Dictionary<string, object> GetJSONObj(string jsonString)
        {
            Dictionary<string, object> userArr = new Dictionary<string, object>();
            try
            {
                JavaScriptSerializer objJS = new JavaScriptSerializer();
                object objStr = objJS.DeserializeObject(jsonString);

                userArr = (System.Collections.Generic.Dictionary<string, object>)objStr;

            }
            catch (Exception ex) { throw ex; }
            return userArr;
        }
         #endregion
     
    }
}

4. After Method Creation Lets add WCF Configuration values in web.config File

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
    <add name="ProjectEntitiesSQLConnStr" connectionString="metadata=res://*/ProjectEntities.csdl|res://*/ProjectEntities.ssdl|res://*/ProjectEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Project;user id=sa;password=admin@123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
  </system.web>
  <!-- Required Configuration For WCF JSON Start  -->
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="NonSoapInspector">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WcfService.MasterSVC">
        <endpoint address="" binding="webHttpBinding" contract="WcfService.IMasterSVC" behaviorConfiguration="NonSoapInspector" name="RESTEndpoint" />
      </service>
    </services>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <!-- Required Configuration For WCF JSON END  -->
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. -->
    <directoryBrowse enabled="true" />
  </system.webServer>
  <!-- Required Configuration For WCF JSON End  -->
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Please note that I am using reference of another project to use ADO.Net entity Framework

5. Now WCF is ready to take JSON Parameter Values

IE WCF Functionality

6. To check functionality I am using POSTER plugin in Firefox
7. First we need to prepare Parameter values for the Method: AddState
Sample JSON string

{
  "AddState": [
    {
      "StateName": "Gujarat",
      "StateCode": "GJ"
    }
  ]
}

8. Now we can upload our parameter values in POSTER add on

FireFox Addon Poster for WCF

9. Poster will return following response from Method

Poster Response

10. We can see that method has inserted new record in Database Table

Databse Record

Advertisement