需求:作为服务方,需要监控每个调用webservice的客户端。需要监控的信息大致如下:客户端的ip,客户端调用了哪个类的哪个方法。
于是自己花了点时间对asp.net的webservice机制作了一下探索。
解决方案: 在接口项目中编写一个所有webservice接口的基类,在此基类的构造方法中,提示通过分析HttpContext.Current.Request得到想要的信息。
1.ip可以通过HttpContext.Current.Request.UserHostAddress得到
2.调用发哪个方法以及参数等都可以通过分析HttpContext.Current.Request.InputStream得到
以下是测试的过程:
先把结论给出:
asp.net的程序在添加对webservice的引用时,客户端会生成代理proxy类。
客户端的调用代码一般类似这样:
ws.Service1 s = new WSWeb.ws.Service1();
s.HelloWorld();
s.MyTestMethod("sssssssssssssttttt");
1.在ws.Service1 s = new WSWeb.ws.Service1();运行这行时,并不会调用服务器端的构造方法,而是调用本地生成的proxy类的构造方法。
2.只有在运行这行时:s.HelloWorld();才会将方法及参数形成soap,绑定到http,发送到服务器端。此时,先调用服务器端的构造方法,然后调用服务器端的HelloWorld
运行第3行s.MyTestMethod("sssssssssssssttttt");时也是这样,会先调一下服务器端的构造方法,再调用服务器端的MyTestMethod。
测试代码: Code
//客户端调用代码
Write("Client端构建对象开始");
ws.Service1 s = new WSWeb.ws.Service1();
Write("Client端构建对象完毕");
Write("Client端开始调用HelloWorld");
s.HelloWorld();
Write("Client端调用HelloWorld完毕");
Write("Client端开始调用MyTestMethod");
s.MyTestMethod("sssssssssssssttttt");
Write("Client端调用MyTestMethod完毕");
Code
Write("进入服务器端基类构造方法");
System.IO.FileInfo fi = new System.IO.FileInfo(PATH);
if (!fi.Exists)
fi.Create();
HttpRequest req = HttpContext.Current.Request;
System.IO.Stream stream = req.InputStream;
stream.Position = 0;
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
StringBuilder sbRequest = new StringBuilder();
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
sbRequest.Append(line + "\n");
}
Write(sbRequest.ToString());
Write("离开 服务器端基类构造方法");
责任编辑:小草