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 = "https://www.jb51.net/"" + data.Rows.Count + "https://www.jb51.net/"";
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将消息反序列化成参数。相对应的客户端代理类也是通过将消息反序列化成对象供客户端使用。
您可能感兴趣的文章: