Gestione e generazione di eccezioni nei servizi Web XML

Le eccezioni generate da un metodo di servizio Web XML creato con ASP.NET vengono restituite al client come un errore SOAP. Un errore SOAP è un elemento XML <Fault> all'interno di un messaggio SOAP in cui è specificato quando si è verificato l'errore. Quando si verifica un errore SOAP, ASP.NET consente di seguire il metodo prestabilito per propagare gli errori al client tramite la specifica SOAP. L'elemento XML SOAP <Fault> contiene informazioni quali la stringa e l'origine dell'eccezione. Per informazioni dettagliate sugli errori SOAP, vedere il sito Web W3C all'indirizzo http://www.w3.org/TR/SOAP (informazioni in lingua inglese).

I client e i servizi Web XML creati con ASP.NET non compilano né analizzano l'elemento XML <Fault> direttamente, ma utilizzano il criterio di progettazione comune per generare e intercettare eccezioni in .NET Framework. Un servizio Web XML è in grado di generare un'eccezione specifica per il problema, quale ArgumentOutOfRangeException o SoapException. In entrambi i casi ASP.NET consente la serializzazione dell'eccezione in un messaggio SOAP valido inserendo tale eccezione in un elemento di errore SOAP. Quando il messaggio SOAP viene deserializzato su un client ASP.NET, l'errore SOAP viene convertito in un'eccezione SoapException, con i relativi dettagli inseriti nella proprietà Message. Un client può quindi impostare un blocco Try/Catch per intercettare un'eccezione SoapException.

In un'applicazione Web possono essere inclusi più servizi Web XML, tuttavia l'evento Application_Error all'interno del file Global.asax non può essere utilizzato per la gestione globale delle eccezioni. L'HttpHandler per i servizi Web XML utilizza qualsiasi eccezione che si verifica quando un servizio Web XML è in esecuzione e la trasforma in un errore SOAP prima della chiamata all'evento Application_Error. Creare un'estensione SOAP per elaborare le eccezioni del servizio Web XML in un gestore globale di eccezioni. Un'estensione SOAP può verificare l'esistenza di un'eccezione nel metodo ProcessMessage. All'interno del metodo ProcessMessage, controllare la proprietà Exception del SoapMessage passato quando la proprietà Stage viene impostata su AfterSerialize. Per ulteriori informazioni sulle estensioni SOAP, vedere Modifica del messaggio SOAP tramite estensioni SOAP.

Generazione di eccezioni da un servizio Web XML creato con ASP.NET

La propagazione di errori al client viene eseguita tramite la generazione di eccezioni. Un metodo di servizio Web XML può eseguire questa operazione in quattro modi:

  1. Generare un'eccezione SoapException.
  2. Generare un'eccezione SoapHeaderException.
  3. Generare un'eccezione specifica per il problema.
  4. Consentire a ASP.NET di generare l'eccezione.

Nella tabella seguente vengono descritte le eccezioni che possono essere generate in modo esplicito da un servizio Web XML e viene illustrato come un client ASP.NET riceve ciascuna eccezione.

Tipo di eccezione generata Funzione di un servizio Web XML
Eccezione diversa da SoapException e SoapHeaderException Un metodo di servizio Web XML rileva un'eccezione e genera sul client l'eccezione specifica, ad esempio ArgumentOutOfRangeException. Un client ASP.NET riceve un'eccezione SoapException con i dettagli serializzati nel testo nella proprietà Message.
SoapException Un metodo di servizio Web XML rileva un'eccezione e genera un'eccezione SoapException. Fornisce inoltre dettagli aggiuntivi relativi al problema. Il metodo di servizio Web XML compila la proprietà Detail per fornire le informazioni aggiuntive. Un client ASP.NET riceve l'eccezione SoapException con informazioni aggiuntive.
SoapHeaderException Un metodo di servizio Web XML rileva un'eccezione durante l'elaborazione di un'intestazione SOAP. Il metodo di servizio Web XML deve generare un'eccezione SoapHeaderException sul client, in base alla specifica SOAP. Un client ASP.NET riceve l'eccezione SoapHeaderException.

Per generare un'eccezione da un servizio Web XML

  • Generare l'eccezione specifica per il problema, quale SoapException, o SoapHeaderException, come descritto nella tabella precedente.

    Nell'esempio di codice seguente viene generata un'eccezione SoapException e vengono forniti dettagli aggiuntivi sull'eccezione impostando la proprietà Detail.

    <%@ WebService Language="VB" class="ThrowSoapException"%>
    
    Imports System
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Imports System.Xml.Serialization
    Imports System.Xml
    
    Public Class ThrowSoapException
        Inherits WebService
    
        ' This XML Web service method throws a SOAP client fault code. 
        <WebMethod()> _
        Public Sub myThrow()
    
            ' Build the detail element of the SOAP fault.
            Dim doc As New System.Xml.XmlDocument()
            Dim node As System.Xml.XmlNode = _            doc.CreateNode(XmlNodeType.Element, _            SoapException.DetailElementName.Name, _            SoapException.DetailElementName.Namespace)
    
            ' Build specific details for the SoapException.
            ' Add first child of detail XML element.
            Dim details As System.Xml.XmlNode = _             doc.CreateNode(XmlNodeType.Element, _            "mySpecialInfo1", "http://tempuri.org/")
    
            ' Add second child of detail XML element with an attribute.
            Dim details2 As System.Xml.XmlNode = _            doc.CreateNode(XmlNodeType.Element, _            "mySpecialInfo2", "http://tempuri.org/")
            Dim attr As XmlAttribute = doc.CreateAttribute("t", _ 
                "attrName", "http://tempuri.org/")
            attr.Value = "attrValue"
            details2.Attributes.Append(attr)
    
            ' Append the two child elements to the detail node.
            node.AppendChild(details)
            node.AppendChild(details2)
    
            'Throw the exception.
            Dim se As New SoapException("Fault occurred", _            SoapException.ClientFaultCode, _            Context.Request.Url.AbsoluteUri, node)
            Throw se
            Return
        End Sub
    End Class
    [C#]
    <%@ WebService Language="C#" class="ThrowSoapException"%>
    
    using System;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Xml.Serialization;
    using System.Xml;
    
    public class ThrowSoapException : WebService 
    {
        // This XML Web service method throws a SOAP client fault code.
        [WebMethod]
        public void myThrow(){
    
            // Build the detail element of the SOAP fault.
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            System.Xml.XmlNode node = doc.CreateNode(XmlNodeType.Element,             SoapException.DetailElementName.Name,              SoapException.DetailElementName.Namespace);
    
            // Build specific details for the SoapException.
            // Add first child of detail XML element.
            System.Xml.XmlNode details =
              doc.CreateNode(XmlNodeType.Element, "mySpecialInfo1",
                             "http://tempuri.org/");
            System.Xml.XmlNode detailsChild =           doc.CreateNode(XmlNodeType.Element, "childOfSpecialInfo",                         "http://tempuri.org/");
            details.AppendChild(detailsChild);
    
            // Add second child of detail XML element with an attribute.
            System.Xml.XmlNode details2 =          doc.CreateNode(XmlNodeType.Element, "mySpecialInfo2",                         "http://tempuri.org/");
            XmlAttribute attr = doc.CreateAttribute("t", "attrName",
                                "http://tempuri.org/");
            attr.Value = "attrValue";
            details2.Attributes.Append(attr);
    
            // Append the two child elements to the detail node.
            node.AppendChild(details);
            node.AppendChild(details2);
    
            //Throw the exception            SoapException se = new SoapException("Fault occurred",          SoapException.ClientFaultCode,          Context.Request.Url.AbsoluteUri ,          node);
    
            throw se;
            return;
        }
    }
    

Per intercettare un'eccezione generata da un metodo di servizio Web XML

  • All'interno di un blocco Try/Catch, intercettare l'eccezione SoapException. Qualsiasi eccezione generata da un metodo di servizio Web XML viene generata come SoapException.

    Nell'esempio di codice seguente viene mostrato un client che chiama un metodo di servizio Web XML e intercetta l'eccezione generata dal metodo di servizio Web XML. Il client compila quindi una tabella HTML con le proprietà dell'eccezione SoapException intercettata.

    <%@ Import Namespace="System.Web.Services.Protocols" %>
    <%@ Import Namespace="System.Xml" %>
    <%@ Page Language="vb" %>
    <html>
     <head>
     <script runat=server language=vb>
        Sub Page_Load(o As Object, e As EventArgs)
           ' Create a new instance of the XML Web service class.
           Dim ThrowsSoapException As ThrowSoapException = New _
                     ThrowSoapException()
           Try
             ThrowsSoapException.myThrow()
           Catch myerr As SoapException
                ' Populate the table with the exception details.
                ErrorTable.Rows.Add(BuildNewRow("Fault Code Namespace", _
                                    myerr.Code.Namespace))
                ErrorTable.Rows.Add(BuildNewRow("Fault Code Name", _
                                    myerr.Code.Name))
                ErrorTable.Rows.Add(BuildNewRow( _
                  "SOAP Actor that threw Exception", myerr.Actor))
                ErrorTable.Rows.Add(BuildNewRow("Error Message", _
                                     myerr.Message))
                ErrorTable.Rows.Add(BuildNewRow("Detail", _
                    HttpUtility.HtmlEncode(myerr.Detail.OuterXml) )) 
                Return
            End Try
        End Sub 'Page_Load
    
        Function BuildNewRow(Cell1Text As String, Cell2Text As String) _
                 As HtmlTableRow
            Dim row As New HtmlTableRow()
            Dim cell1 As New HtmlTableCell()
            Dim cell2 As New HtmlTableCell()
    
            'Set the contents of the two cells.
            cell1.Controls.Add(New LiteralControl(Cell1Text))
            'Add the cells to the row.
            row.Cells.Add(cell1)
    
            cell2.Controls.Add(New LiteralControl(Cell2Text))
    
            'Add the cells to the row.
            row.Cells.Add(cell2)
            Return row
        End Function 'BuildNewRow 
     </script>
     <head>
     <body>
         <table id="ErrorTable" CellPadding=5 CellSpacing=0 Border="1" BorderColor="black" runat="server" />
     </body>
    [C#]
    <%@ Import Namespace="System.Web.Services.Protocols" %>
    <%@ Import Namespace="System.Xml" %>
    <%@ Page Language="C#" %>
    <html>
     <head>
     <script runat=server language=c#>
     void Page_Load(Object o, EventArgs e){
    
       // Create a new instance of the XML Web service proxy class.
       ThrowSoapException throwSoapException = new ThrowSoapException();
    
       // Make a call to the XML Web service method, which throws an
       // exception.
        try
        {
           throwSoapException.myThrow();
        }
        catch (SoapException error)     {
           // Populate the table with the exception details.
           ErrorTable.Rows.Add(BuildNewRow("Fault Code Namespace",
                                            error.Code.Namespace));
           ErrorTable.Rows.Add(BuildNewRow("Fault Code Name",
                                            error.Code.Name)); 
           ErrorTable.Rows.Add(BuildNewRow(
              "SOAP Actor that threw Exception", error.Actor));
           ErrorTable.Rows.Add(BuildNewRow("Error Message",
               error.Message));
           ErrorTable.Rows.Add(BuildNewRow("Detail",
               HttpUtility.HtmlEncode(error.Detail.OuterXml)));
    
           return;
         }
    
     }
    // This populates a row in an HtmlTable.
     HtmlTableRow BuildNewRow(string Cell1Text, string Cell2Text) {
         HtmlTableRow row = new HtmlTableRow();
         HtmlTableCell cell1 = new HtmlTableCell();
         HtmlTableCell cell2 = new HtmlTableCell();
    
         //Set the contents of the two cells.
         cell1.Controls.Add(new LiteralControl(Cell1Text));
         //Add a cell to the row.
         row.Cells.Add(cell1);
    
         cell2.Controls.Add(new LiteralControl(Cell2Text));
    
         //Add a cell to the row.
         row.Cells.Add(cell2);
         return row;
    
     }
     </script>
     <head>
     <body>
         <table id="ErrorTable" CellPadding=5 CellSpacing=0 Border="1" BorderColor="black" runat="server" />
     </body>
    

Eccezioni non gestite da un metodo di servizio Web XML

Nella tabella seguente viene illustrato come vengono gestite le eccezioni da ASP.NET quando un metodo di servizio Web XML non intercetta un'eccezione che si verifica all'interno del metodo.

Quando si verificano eccezioni non gestite Funzionamento di ASP.NET
Durante l'esecuzione del metodo di servizio Web XML L'eccezione viene intercettata da ASP.NET e generata sul client. Il client del servizio Web XML creato con .NET Framework riceve SoapException con l'eccezione specifica inserita nella proprietà InnerException.
Durante l'elaborazione di intestazioni SOAP ASP.NET genera un'eccezione SoapHeaderException. Un client del servizio Web XML creato con .NET Framework riceve l'eccezione SoapHeaderException.

Vedere anche

Classe SoapException | Classe SoapHeaderException | Gestione e generazione di eccezioni | Generazione di servizi Web XML mediante ASP.NET | Generazione di client dei servizi Web XML