WCF – Request and Response in JSON format using WebInvoke attribute

By default, WCF service application supports request and response in SOAP format. Many times we have requirements that consumer of WCF service wants request and response in JSON format (REST). So it means we need to make some configuration in WCF service to support JSON format.

Here I’ve enlist steps which will help you in getting request and response in JSON format.

Example: Bank has many entities, operations etc. but here, we will focus on only getting Account detail of user.

  1. Lets create WCF application. You can give any name to your project. Here, I have gave “BankService”.
Create WCF application
Created BankService WCF service application with .Net framework 4.6.1

2. I’ve created an interface called “IAccountService”. Responsibility of this interface/service/API will be to perform all operations related to account like GetDetail(…), Create(…) etc. Here, GetDetail(…) operation will give us Account details based on accountNumber.

Exposed IAccountService interface
IAccountService exposed interface to the outer world.
Account contract
Account contract

3. There is an attribute called WebInvoke (System.ServiceModel.Web namespace). You need to decorate your operation with this attribute.

WebInvoke1
WebInvoke attribute

You need to set below properties to work with JSON.

Method: “GET”, “POST”, “PUT”, “DELETE”. “POST” is default

BodyStyle: Can be Bare, Wrapped, WrappedRequest or WrappedResponse. You can use any bodystyle based on your need. WrappedRequest means only request needs to be wrapped. Wrapped means both request and response will be wrapped. WrappedResponse means response from service will be wrapped. Bare means request and response are not wrapped.

RequestFormat: WebMessageFormat.Json or WebMessageFormat.XML. Here, you need to set WebMessageFormat.Json

ResponseFormat: WebMessageFormat.Json or WebMessageFormat.XML. Here, you need to set WebMessageFormat.Json

4. Lets implement this interface.

BankAccountService
Bank account service implementation

You need to make few more configuration in web.config file of WCF service. When you create your project, by default, you will get WsHttpBinding but here, you need to create your own httpBinding for json format.  Modify your web.config file as below.

web_servicemodel full
Web.config file of service

You are done with the all configurations. Its time to fly now! I’ve tested it with Postman tool. You can see response from service in second section of image.

Capture
Request and Response

Leave a Reply

Your email address will not be published. Required fields are marked *