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

1 篇文章 0 订阅
1 篇文章 0 订阅


本文属于个人转载,原文转载地址:http://www.codeproject.com/Articles/386956/RestFul-WCF-JSON-Service-with-client-and-on-Mozill


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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值