REST WCF 使得我們調用Web服務時,可以通過HttpRequest的交互簡單完成。那麼老版的WebService能否做到呢?WebService中通過HttpContext.Current.Rquest/Response,我們一樣也可以改造WebMethod。
客戶端:
復制代碼 代碼如下:
// 創建一個DataTable
DataTable data = new DataTable("Project");
data.Columns.Add("Name");
data.Columns.Add("Birthday");
data.Rows.Add(new object[] { "Wendy", "1978/03/11" });
data.Rows.Add(new object[] { "Philip", "2000/11/05" });
data.Rows.Add(new object[] { "Felix", "1999/08/04" });
using (var ms = new MemoryStream())
{
// 將DataTable用Xml格式寫入流
data.WriteXml(ms, XmlWriteMode.WriteSchema);
var client = new WebClient();
// 定義HttpRequest的Content-Type(xml,json等)
client.Headers.Add("Content-Type", "text/xml");
var url = "http://localhost:2609/Service1.asmx/SendXml";
// Send HttpRequest
var resp = client.UploadData(url, "POST", ms.ToArray());
var strResp = System.Text.Encoding.UTF8.GetString(resp);
MessageBox.Show(strResp);
}
服務端:
復制代碼 代碼如下:
[WebMethod]
public void SendXml()
{
// 獲得客戶端RAW HttpRequest
var inputStream = HttpContext.Current.Request.InputStream;
// 定義Response返回的格式是:Json
var response = HttpContext.Current.Response;
response.ContentType = "text/json";
//var strXml = "";
//using (var sr = new StreamReader(inputStream))
// strXml = sr.ReadToEnd();
try
{
DataTable data = new DataTable();
using (var xr = XmlReader.Create(inputStream))
data.ReadXml(xr);
// 將讀入Xml的DataTable的行數返回客戶端
string count = "/"" + data.Rows.Count + "/"";
response.BinaryWrite(System.Text.Encoding.UTF8.GetBytes(count));
}
catch (Exception ex)
{
response.BinaryWrite(System.Text.Encoding.UTF8.GetBytes(ex.Message));
}
}
客戶端輸出""3""
PS: 如果客戶端的HttpRequest滿足SOAP序列化格式,WebService會為WebMethod將消息反序列化成參數。相對應的客戶端代理類也是通過將消息反序列化成對象供客戶端使用。