使用Elmah处理Web服务中的异常

时间:2010-02-01 21:31:47

标签: asp.net web-services asmx elmah

有没有办法使用ELMAH全局处理常规ASP.NET Web服务(asmx)中的异常,就像我们在ASP.NET网站中一样?

3 个答案:

答案 0 :(得分:25)

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));
  }
}

答案 1 :(得分: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,你感兴趣的那个可能是内部异常。

答案 2 :(得分:0)

您可以使用此代码

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

            }