Click here to Skip to main content
Click here to Skip to main content

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

, 18 May 2012
Rate this:
Please Sign up or sign in to vote.
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

[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):

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

Code

//================ 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

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/

Testing:

License

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

About the Author

Himanshu Thawait
Technical Lead
United States United States
Himanshu Thawait is from Pune INDIA, He is Currently Working with Cognizant. As a Technical Designer and Lead
 
Himanshu has more than 9+ yrs of experience in the IT industry working on Microsoft Technologies. He is involved in various project activities like designing the system and technical architecture,leading technical front and doing core development.He also has strong knowledge of Enterprise Business Application Domain.
 
Technical experience :C#, ASP.NET MVC 4 @Razor, WCF and Webservices, Biztalk 2010/2009/2006R2 with EDI(HIPPA).

Comments and Discussions

 
GeneralNice doc and very useful to me PinmemberJainith Patel5-Apr-14 5:34 
QuestionCan we out parameter for the methods? PinmemberDurga Venkata Prasad15-Jan-14 5:00 
QuestionRe: Can we out parameter for the methods? PinmemberHimanshu Thawait15-Feb-14 14:08 
AnswerRe: Can we out parameter for the methods? PinmemberDurga Venkata Prasad13-May-14 23:29 
AnswerRe: Can we out parameter for the methods? PinpremiumHimanshu Thawait16-Jul-14 11:01 
Generalnice Pinprofessionalwaseem mak24-Oct-13 1:25 
QuestionNeed to call third party API from SL 5 project PinmemberTbhavesh13-Aug-12 10:03 
AnswerRe: Need to call third party API from SL 5 project PinmemberHimanshu Thawait14-Aug-12 12:24 
GeneralRe: Need to call third party API from SL 5 project PinmemberTbhavesh16-Aug-12 8:33 
GeneralRe: Need to call third party API from SL 5 project PinmemberHimanshu Thawait16-Aug-12 8:49 
GeneralMy vote of 5 PinmemberRahul Rajat Singh10-Jun-12 19:02 
GeneralMy vote of 1 Pinmembereddy morrison22-May-12 2:09 
Questionعادل عبدة درجان Pinmemberadel abdo drajan20-May-12 5:00 
اسلام عليكم الو سمحت اريد تحليل عنbrow ser
AnswerRe: عادل عبدة درجان PinmemberAnand Todkar9-Jan-13 17:52 
GeneralMy vote of 5 PinmemberMonjurul Habib18-May-12 8:55 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 18 May 2012
Article Copyright 2012 by Himanshu Thawait
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid