2010-02-01 105 views

回答

23

ASP.NET Web服務永遠不會觸發Application_Error事件和異常不能在全球範圍內通過ELMAH像在ASP.NET應用程序進行處理。但是,我們可以在「手動」使用ELMAH記錄異常:

 

public int WebServiceMethod() { 
    try { 
    ... 
    } 
    catch (Exception ex) { 
    Elmah.ErrorLog.GetDefault(
     HttpContext.Current).Log(new Elmah.Error(ex, HttpContext.Current)); 
    } 
} 
 
+0

這就是我想,但我檢查,如果有一個「乾淨」的解決方案。謝謝 – 2010-02-02 18:17:43

+0

是的,更清潔的解決方案或練習對我來說也會很有趣。這是個好問題(+1)。 – 2010-02-02 19:03:39

+0

我終於使用了你的解決方案,我沒有找到一個更好的方法來做到這一點。感謝提示。 – 2010-03-23 12:57:17

23

可以使用的SoapExtension做到這一點:

using System; 
using System.Web.Services.Protocols; 

namespace MyNamespace 
{ 
    class ELMAHExtension : SoapExtension 
    { 
     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.Stage == SoapMessageStage.AfterSerialize && 
       message.Exception != null) 
      { 
       // Log exception here 
      } 
     } 
    } 
} 

您在以下行的web.config中註冊該

<system.web> 
    <webServices> 
    <soapExtensionTypes> 
     <add type="MyNamespace.ELMAHExtension, MyDLL" priority="1" group="1" /> 
    </soapExtensionTypes> 
    </webServices> 
</system.web> 

這會給你訪問的HttpContext和的SOAPMessage對象應該給你所有你需要了解正在叫什麼細節。我認爲在這個階段你檢索到的異常將永遠是一個SoapException,你感興趣的位可能是內部的異常。

+0

謝謝,我會嘗試。 – 2010-07-10 12:05:09

+1

還沒有有機會尚未嘗試這一點,但它_looks_喜歡它應該工作。它說: '在這裏記錄異常' 代碼'Elmah.ErrorLog.GetDefault( HttpContext.Current).LOG(新Elmah.Error(例如,HttpContext.Current));'可能做的伎倆。 – codeulike 2011-01-12 13:57:39

+0

事實上,它確實有效。 – avesse 2012-06-22 08:00:43

0

您可以使用此代碼

try{ 
// your code in here 
} 
    catch (Exception ert) 
      { 
       Elmah.ErrorSignal.FromCurrentContext().Raise(ert); 

      }