首页 / 网页编程 / ASP.NET / 无侵入方面编程-用HttpModule+SoapExtension监视页面执行参数(一)
无侵入方面编程-用HttpModule+SoapExtension监视页面执行参数(一)2009-12-31 博客园 阿牛先简单介绍一下项目吧,我们这个项目是用VS2003开发的,老早一个项目。WEB前端机+业务处理 (WebService层)+数据库分别布置在不同的计算机上。现在老总有一个需求,要统计出每个页 面的执行时间,以及每次调用过哪些WebService方法,调用的时间等参数。可行的方案有好多, 但我感觉使用HttpModule+SoapExtension,可以不在改变目标系统源码的基础上,完成这项工作。也许 有一天,老总说,现在不需要再统计了,我就直接配置一下,不再统计就行了。由于要调用 WebService,我们采用编写一个SoapExtension,在它的ProcessMessage函数中,在message.Stage是 BeforeSerialize 时,记一个开始时间,并采集一些数据,在message.Stage==AfterDeserialize时, 再采集一些时间等数据。最后通过HttpContext.Current.Items[WSInvokeMonitorKey]获取HttpModule的 对象,把采集到的数据放在HttpModule里面。在HttpModule层,我们可以context的 BeginRequest、PreRequestHandlerExecute、PreSendRequestContent、EndRequest中采集数据,最后写 入通过Log4net写入日志文件。具体实现起来,应该很简单,高手可以略过了。先看看如 何使用吧,只需在Web.Config中加一条配置:<configuration> <system.web> <httpModules> <add name="WSInvokeMonitorHttpModule" type="Hebmc.WebTools.WSInvokeMonitor.WSInvokeMonitorHttpModule,WSInvokeMonitor"/& gt; </httpModules> <webServices> <soapExtensionTypes> <add type="Hebmc.WebTools.WSInvokeMonitor.SimpleWSInvokeMonitorExtension,WSInvokeMonitor&qu ot; priority="1" group="0" /> </soapExtensionTypes> </webServices> </system.web> </configuration>SoapExtension实现:SoapExtension public class SimpleWSInvokeMonitorExtension : SoapExtension { private const string WSInvokeMonitorKey = "__WSInvokeMonitorKey__"; private WSInvokeInfo invokeInfo = new WSInvokeInfo(); public override System.IO.Stream ChainStream (System.IO.Stream stream) { return stream; } public override object GetInitializer(Type serviceType) { return null; } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override void Initialize (object initializer) { } public override void ProcessMessage(SoapMessage message) { if(message is SoapClientMessage) { switch (message.Stage) { case SoapMessageStage.BeforeSerialize: // 采集时间 this.invokeInfo.BeginInvokeTime = DateTime.Now; //采集WebService方法名 this.invokeInfo.MethodName = message.MethodInfo.Name; break; case SoapMessageStage.AfterSerialize: break; case SoapMessageStage.BeforeDeserialize: break; // About to call methods case SoapMessageStage.AfterDeserialize: //采集时间 this.invokeInfo.EndInvokeTime = DateTime.Now; PageInfo pageInfo = (PageInfo) HttpContext.Current.Items[WSInvokeMonitorKey] ; if(pageInfo != null) { //添 加到Module记录 pageInfo.AppendInvokeInfo(this.invokeInfo); } break; // After Method call default: throw new Exception("No stage such as this"); } } else if(message is SoapServerMessage) { switch (message.Stage) { case SoapMessageStage.BeforeDeserialize: break; case SoapMessageStage.AfterDeserialize: break; case SoapMessageStage.BeforeSerialize: break; case SoapMessageStage.AfterSerialize: break; default: throw new Exception ("No stage such as this"); } } } }
收藏该网址