【发布时间】:2011-01-11 22:06:11
【问题描述】:
有没有办法像我们在 ASP.NET 网站中那样使用 ELMAH 来全局处理常规 ASP.NET Web 服务 (asmx) 中的异常?
【问题讨论】:
标签: asp.net web-services asmx elmah
有没有办法像我们在 ASP.NET 网站中那样使用 ELMAH 来全局处理常规 ASP.NET Web 服务 (asmx) 中的异常?
【问题讨论】:
标签: asp.net web-services asmx elmah
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));
}
}
【讨论】:
您可以使用 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,而您感兴趣的部分可能是内部异常。
【讨论】:
Elmah.ErrorLog.GetDefault( HttpContext.Current).Log(new Elmah.Error(ex, HttpContext.Current)); 可能会起作用。
group="1" 有效吗? Intellisense 建议您需要“低”或“高”。
您可以使用此代码
try{
// your code in here
}
catch (Exception ert)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ert);
}
【讨论】: