Click here to Skip to main content
15,881,281 members
Articles / Web Development / ASP.NET

RestFul WCF JSON Service with client and on Mozilla Firefox –REST Client

Rate me:
Please Sign up or sign in to vote.
4.94/5 (13 votes)
18 May 2012CPOL1 min read 112.3K   8.7K   49   18
WCF REStful service -with GET, PUT, POST and DELETE Method and testing on Mozilla Firefox –REST Client

Introduction 

This article will talk about

  • WCF REStful service: with GET, PUT, POST, and DELETE methods
  • Web Invoke: Request response on JSON
  • See response on console in raw format
  • Testing on Mozilla Firefox – REST client
  • Automatic format selection for JSON/XML 

Background

The RESTful web service is hosted on IIS. This service will take request and response on JSON. There is no business logic, this is just demo code. Let's see how to prepare a request for GET, PUT, POST, and DELETE methods. With a lot of combination of input parameters and return type. Like take string return object, take object return object, etc.

Server side: Service

C#
[ServiceContract]
public interface IService1
{
	//GET - /// Simplet GET method with no parameret and return primitive type
    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "/GetNoPara", 
          RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string HelloWorld();

    /// GET Methos with parameter and return the Object
  	[OperationContract]
  	[WebInvoke(Method = "GET", UriTemplate = "/GetDataJSON/{value}", 
  	  RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    CompositeType GetDataJSON(string value);


	//POST
    /// Simple POST with primitive IN, OUT
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/PostString", 
          RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    bool PostTest(string value);
        
    /// POST Method whic accept Object as input and return Object 
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/PostCompositeType", 
            RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    //PUT
    /// Simple PUT with primitive IN, OUT
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "/PutString", 
      RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string PutString(string value);

    /// PUT Method whic accept Object as input and return string 
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "/PutCompositeType", 
               RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string PutCompositeType(CompositeType composite);
    //DELETE
    /// DELETE Method whic accept string as input and return string  
    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "/DeleteString", 
      RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string DeleteString(string value);

    /// DELETE Method whic accept object as input and return Object  
    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "/DeleteCompositeType", 
      RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    CompositeType DeleteCompositeType(string value);

Web.config

Setting for automatic format selection for JSON/XML – Just add the following on Web.config serviceBehaviors. This will automatically set the response format as per request type (JSON/XML):

XML
<endpointBehaviors>
    <behavior name="web">
        <webHttp automaticFormatSelectionEnabled="true"/>
    </behavior>
</endpointBehaviors>

Client side: WCF client

The C# Win application is going consume this service and we can see the response in raw data format for JSON and XML.

Image 1

Code

C#
//================ GET========================
private void GetHello_Click(object sender, EventArgs e)
{
    WebClient WC = new WebClient();
    byte[] res1 = WC.DownloadData(ServiceUrl + "GetNoPara");

    Stream res2 = new MemoryStream(res1);
    DataContractJsonSerializer res3 = new DataContractJsonSerializer(typeof(string));
    string response = res3.ReadObject(res2).ToString();

    Console.WriteLine(response);
}

private void HelloToMe_Click(object sender, EventArgs e)
{
    GetData(ServiceUrl + "GetDataJSON/" + txtMyName.Text, "JSON");

    WebClient WC = new WebClient();
    byte[] res1 = WC.DownloadData(ServiceUrl + "GetDataJSON/" + txtMyName.Text);

    Stream res2 = new MemoryStream(res1);
    DataContractJsonSerializer res3 = new DataContractJsonSerializer(typeof(CompositeType));
    CompositeType CT = (CompositeType)res3.ReadObject(res2);

    Console.WriteLine(CT.StringValue);
}

//=================== POST ==========================
private void PassObject_Click(object sender, EventArgs e)
{

    WebClient WC = new WebClient();
    WC.Headers["Content-type"] = "application/json";

    CompositeType CT = new CompositeType();
    CT.BoolValue = true;
    CT.StringValue = txtMyName.Text;

    MemoryStream MS = new MemoryStream();
    DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(CompositeType));

    JSrz.WriteObject(MS, CT);

    byte[] res1 = WC.UploadData(ServiceUrl + 
      "PostCompositeType", "POST", MS.ToArray());

    Stream res2 = new MemoryStream(res1);
    JSrz = new DataContractJsonSerializer(typeof(CompositeType));

    CT = (CompositeType)JSrz.ReadObject(res2);

    Console.WriteLine(CT.StringValue);
}

private void PostTest_Click(object sender, EventArgs e)
{
    WebClient WC = new WebClient();
    WC.Headers["Content-type"] = "application/json";

    MemoryStream MS = new MemoryStream();
    DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(string));

    JSrz.WriteObject(MS, txtMyName.Text);

    byte[] res1 = WC.UploadData(ServiceUrl + "PostString", "POST", MS.ToArray());

    MS = new MemoryStream(res1);
    JSrz = new DataContractJsonSerializer(typeof(bool));
    bool result = (bool)JSrz.ReadObject(MS);

    Console.WriteLine(result);
}

#================== PUT =====================

private void PutString_Click(object sender, EventArgs e)
{
    WebClient WC = new WebClient();
    WC.Headers["Content-type"] = "application/json";

    MemoryStream MS = new MemoryStream();
    DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(string));

    JSrz.WriteObject(MS, txtMyName.Text);
    byte[] res1 = WC.UploadData(ServiceUrl + "PutString", "PUT", MS.ToArray());

    MS = new MemoryStream(res1);
    JSrz = new DataContractJsonSerializer(typeof(string));
    string result = (string)JSrz.ReadObject(MS);

    Console.WriteLine(result);
}

private void PutCompositeType_Click(object sender, EventArgs e)
{
    WebClient WC = new WebClient();
    WC.Headers["Content-type"] = "application/json";

    CompositeType CT = new CompositeType();
    CT.BoolValue = true;
    CT.StringValue = txtMyName.Text;

    MemoryStream MS = new MemoryStream();
    DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(CompositeType));

    JSrz.WriteObject(MS, CT);

    byte[] res1 = WC.UploadData(ServiceUrl + "PutCompositeType", "PUT", MS.ToArray());

    Stream res2 = new MemoryStream(res1);
    JSrz = new DataContractJsonSerializer(typeof(string));

    string result = (string)JSrz.ReadObject(res2);

    Console.WriteLine(result);

}

#=================== DELETE ==========================

private void DELETEString_Click(object sender, EventArgs e)
{

    WebClient WC = new WebClient();
    WC.Headers["Content-type"] = "application/json";

    MemoryStream MS = new MemoryStream();
    DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(string));


    JSrz.WriteObject(MS, txtMyName.Text);

    byte[] res1 = WC.UploadData(ServiceUrl + "DeleteString", "DELETE", MS.ToArray());

    MS = new MemoryStream(res1);
    JSrz = new DataContractJsonSerializer(typeof(string));
    string result = (string)JSrz.ReadObject(MS);

    Console.WriteLine(result);

}

private void DELETECompositeType_Click(object sender, EventArgs e)
{
    WebClient WC = new WebClient();
    WC.Headers["Content-type"] = "application/json";

    MemoryStream MS = new MemoryStream();
    DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(string));

    JSrz.WriteObject(MS, txtMyName.Text);

    byte[] res1 = WC.UploadData(ServiceUrl + "DeleteCompositeType", "DELETE", MS.ToArray());

    MS = new MemoryStream(res1);
    JSrz = new DataContractJsonSerializer(typeof(CompositeType));
    CompositeType CT = (CompositeType)JSrz.ReadObject(MS);

    Console.WriteLine(CT.StringValue);
}

GET (same endpoint) automaticFormatSelectionEnabled

C#
private void getDataJSON_Click(object sender, EventArgs e)
{
    GetData("JSON");
}

private void getDataXML_Click(object sender, EventArgs e)
{
    GetData("XML");
}

private void GetData(string ResponseType)
{
    string URL = ServiceUrl + "AutoFormatPost/H";
    GetData(URL, ResponseType);
}

private void GetData(string URL, string ResponseType)
{
    WebClient client = new WebClient();
    client.Headers["Content-type"] = 
      @"application/" + ResponseType;
    Stream data = client.OpenRead(URL);
    StreamReader reader = new StreamReader(data);
    string str = "";
    str = reader.ReadLine();

    Console.WriteLine("******* Raw Response *******");

    while (str != null)
    {
        Console.WriteLine(str);
        str = reader.ReadLine();
    }
    data.Close();

}

Testing on Mozilla Firefox –REST Client

Mozilla Firefox will provide a tool to test a RESTful service and here we will see how to get that and use the same.

How to get and install: https://addons.mozilla.org/en-US/firefox/addon/restclient/

Image 2

Testing:

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Sapient Global Market
United States United States
Himanshu Thawait is Associate Arch at Sapient Global Markets.

He is expert in developing EAI, BizTalk with EDI(HIPPA)., Web applications, Micro web services, Angular, ASP.NET MVC, C#, VB.NE T, VB 6, SQL Server, Oracle, No SQL, Classic ASP, XML and JavaScript, IBM MQSC, IBM DB2.

Comments and Discussions

 
Questionhow can we add the service reference of my WCF REST service to my cleint App. Pin
Member 334102821-Sep-15 1:28
Member 334102821-Sep-15 1:28 
QuestionHow to user List<ComplexType> as a parameter in POST Method. Pin
Rocky2326-Sep-14 4:58
Rocky2326-Sep-14 4:58 
AnswerRe: How to user List<ComplexType> as a parameter in POST Method. Pin
Himanshu Thawait30-Sep-14 11:09
Himanshu Thawait30-Sep-14 11:09 
GeneralNice doc and very useful to me Pin
Jainith Patel5-Apr-14 5:34
Jainith Patel5-Apr-14 5:34 
QuestionCan we out parameter for the methods? Pin
Durga Venkata Prasad15-Jan-14 5:00
Durga Venkata Prasad15-Jan-14 5:00 
QuestionRe: Can we out parameter for the methods? Pin
Himanshu Thawait15-Feb-14 14:08
Himanshu Thawait15-Feb-14 14:08 
AnswerRe: Can we out parameter for the methods? Pin
Durga Venkata Prasad13-May-14 23:29
Durga Venkata Prasad13-May-14 23:29 
AnswerRe: Can we out parameter for the methods? Pin
Himanshu Thawait16-Jul-14 11:01
Himanshu Thawait16-Jul-14 11:01 
Generalnice Pin
Waseem-Malik24-Oct-13 1:25
professionalWaseem-Malik24-Oct-13 1:25 
QuestionNeed to call third party API from SL 5 project Pin
Tbhavesh13-Aug-12 10:03
Tbhavesh13-Aug-12 10:03 
AnswerRe: Need to call third party API from SL 5 project Pin
Himanshu Thawait14-Aug-12 12:24
Himanshu Thawait14-Aug-12 12:24 
GeneralRe: Need to call third party API from SL 5 project Pin
Tbhavesh16-Aug-12 8:33
Tbhavesh16-Aug-12 8:33 
GeneralRe: Need to call third party API from SL 5 project Pin
Himanshu Thawait16-Aug-12 8:49
Himanshu Thawait16-Aug-12 8:49 
GeneralMy vote of 5 Pin
Rahul Rajat Singh10-Jun-12 19:02
professionalRahul Rajat Singh10-Jun-12 19:02 
GeneralMy vote of 1 Pin
eddy morrison22-May-12 2:09
eddy morrison22-May-12 2:09 
Questionعادل عبدة درجان Pin
adel abdo drajan20-May-12 5:00
adel abdo drajan20-May-12 5:00 
AnswerRe: عادل عبدة درجان Pin
Anand Todkar9-Jan-13 17:52
Anand Todkar9-Jan-13 17:52 
GeneralMy vote of 5 Pin
Monjurul Habib18-May-12 8:55
professionalMonjurul Habib18-May-12 8:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.