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));
}
}
PS: 如果客户端的HttpRequest满足SOAP序列化格式,WebService会为WebMethod将消息反序列化成参数。相对应的客户端代理类也是通过将消息反序列化成对象供客户端使用。