請找一些示例代碼,讓您的工作場景:
在我的服務器:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string CreateInvoice(Stream xmlStream)
{
byte[] buffer = new byte[WebOperationContext.Current.IncomingRequest.ContentLength];
int read = -1;
while (read != 0)
{
read = xmlStream.Read(buffer, 0, buffer.Length);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string jsonobjectstring = enc.GetString(buffer);
JavaScriptSerializer json = new JavaScriptSerializer();
object jsonobject = json.DeserializeObject(jsonobjectstring);
return "Recieved the json text on server";
//MaintainInvoice(xmlStream, InvoiceMaintainance.CreateInvoice);
}
我已經修改了服務器的方法,邏輯,這樣我就可以測試它。一旦在服務器上獲得流,您可以根據需要使用邏輯返回發票對象。
在客戶端我們可以調用其他服務,我使用下面的代碼:
private string UseHttpWebApproachByteArray(string serviceUrl, string resourceUrl, string method, byte[] requestBody)
{
string responseMessage = null;
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/octet-stream";
request.Method = method;
}
if (method == "POST" && requestBody != null)
{
request.ContentLength = requestBody.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBody, 0, requestBody.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
return responseMessage;
}
private void Test()
{
string jsonText = "{\"invoices\":{\"POSWorkstationID\":\"POS7\",\"POSClerkID\":\"admin\",\"CustomerName\":\"Alice in Wonderland Tours\",\"IsFreightOverwrite\":true},\"invoiceDetails\":[{\"ItemDescription\":\"Old World Lamppost\",\"QuantityOrdered\":\"1\",\"SalePriceRate\":\" $107.99\",\"ExtPriceRate\":\"107.99\",\"ItemType\":\"Stock\",\"LineNum\":1,\"WarehouseCode\":\"Main\"}]}";
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] jsonBytes = enc.GetBytes(jsonText);
UseHttpWebApproachByteArray(serviceBaseUrl, resourceUrl, method, jsonBytes);
}
爲什麼要送它作爲流的任何具體的原因是什麼?你也可以發佈DataContract發票 – Rajesh 2012-03-07 09:41:23