Asp.net

IIS 7 日誌記錄 Web 服務方法

  • April 4, 2017

我有一個託管在 IIS 7 下的 Web 服務(不是 WCF 服務),該 Web 服務有兩種方法:method1 和 method2。

我希望在不修改 Web 服務程式碼的情況下區分對方法 1 的請求與對方法 2 的請求。

在 IIS 7 日誌下,我可以看到對 Web 服務的請求,Web 服務 URL 記錄在“cs-uri-stem”欄位下,但“cs-uri-query”欄位為空。

無論如何都可以在不修改 Web 服務程式碼的情況下記錄 Web 服務方法的請求?

您可以在處理管道的各種方法中記錄所有傳入請求。例如,BeginRequest在您的 中添加一個處理程序Global.asax

Application_BeginRequest( object sender, EventArgs e )
{
   HttpApplication app = (HttpApplication)sender;
   HttpContext ctx = app.Context;

   var requestUrl = ctx.Request.Url;

   // the uri should be of a form:
   // http://yoursite/theservice.asmx/MethodName
}

多年後,我不得不訪問具有數百種方法的 ASMX,但無法轉換為 WCF。這是一個 ASMX 擴展點,它允許您在不訪問所有方法的情況下記錄方法名稱。在這裡,我使用 log4net 來記錄方法名稱,YMMV

首先,創建一個 SoapExtension 類:

namespace MyNamespace {
   public class WebMethodLogger : SoapExtension
   {
       private static readonly ILog _log = LogManager.GetLogger(typeof(WebMethodLogger));

       public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
       {
           return null; //No state
       }

       public override object GetInitializer(Type serviceType)
       {
           return null; //No state
       }

       public override void Initialize(object initializer)
       {
           //Do nothing
       }

       public override void ProcessMessage(SoapMessage message)
       {
           if (message.Stage == SoapMessageStage.AfterDeserialize)
               _log.Debug(message.MethodInfo.MethodInfo.Name);
       }
   }
}

然後,在 web.config 中註冊擴展:

<system.web>
...
   <webServices>
       <soapExtensionTypes>
           <add type="MyNamespace.WebMethodLogger, MyAssembly"
                priority="1"
                group="High" />
       </soapExtensionTypes>
   </webServices>
...
</system.web>

引用自:https://stackoverflow.com/questions/8992265