Handle exceptions in web services with Elmah

后端 未结 3 613
[愿得一人]
[愿得一人] 2020-12-09 08:05

Is there a way to globally handle exceptions in regular ASP.NET Web Service (asmx) using ELMAH like we do it in ASP.NET web site ?

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 08:31

    You can use a SoapExtension to do this :

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

    You register this in the web.config with the following lines :

    
      
        
          
        
      
    
    

    This will give you access to the HttpContext and SoapMessage objects which should give you all of the details you need about what was being called. I think the exception you retrieve at this stage will always be a SoapException and that the bit you are interested in is probably the inner exception.

提交回复
热议问题