您的位置:首页 > Web前端 > JavaScript

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

2015-10-24 14:57 651 查看


本文属于个人转载,原文转载地址: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

Hide Shrink


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

Hide Copy Code
<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

Hide Shrink


Copy 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

Hide Shrink


Copy Code
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:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: