7

I wrote the following service :

namespace WebService1
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string Test(string str)
        {
            if (string.IsNullOrEmpty(str))
                throw new SoapException("message", SoapException.ClientFaultCode);
            else
                return str;
        }
    }
}

And a basic application to test it (one button calling the Test method on click event):

private void button1_Click(object sender, EventArgs e)
{
    ServiceReference1.Service1SoapClient ws = new WindowsFormsApplication1.ServiceReference1.Service1SoapClient();

    try
    {
        ws.Test("");
    }
    catch (SoapException ex)
    {
         //I never go here
    }
    catch (FaultException ex)
    {
        //always go there
    }
    catch (Exception ex)
    {

    }
}

I'd like to catch the SoapException thrown by my WebService, but I always go to the FaultException catch block a get that as message:

System.Web.Services.Protocols.SoapException: message at WebService1.Service1.Test(String str) in [...]WebService1\WebService1\Service1.asmx.cs:line 25

How could I catch a real SoapException, and not a FaultException? Is there something I miss in the WebService?

shA.t
  • 16,580
  • 5
  • 54
  • 111
Sharpac
  • 418
  • 3
  • 5
  • 13

2 Answers2

8

I think that the main "problem" is that you are using a WCF Service Reference connecting to an ASP.NET Web Service (.asmx).

The "easiest" way to handle this would probably be to use a Web Reference instead of a WCF Service Reference on the client. You do this by selecting the "Advanced" button on the bottom of the Add Service Reference dialog, and then the Add Web Reference on the bottom of that screen. I believe that using a Web Reference should give you a SoapException.

The correct way (if you want to follow Microsofts advice) would be to publish a WCF service instead of an .asmx service. That is a whole other chapter though..

CodingInsomnia
  • 1,843
  • 2
  • 15
  • 19
  • 1
    -1: it's not necessary to use old technology on the client just because old technology is used on the server. – John Saunders Feb 17 '11 at 14:42
  • 4
    True, it is certainly not necessary. However, mixing WCF and ASMX is a sure way of getting in a heap of trouble. Did you have a better solution? If so, I'm sure that Sharpac would be interested in hearing it, and so would I... – CodingInsomnia Feb 17 '11 at 14:45
  • Thanks CodingInsomnia that's works! I finally catch a SoapException. – Sharpac Feb 17 '11 at 14:51
6

When an ASMX service throws a SoapException, .NET returns a SOAP Fault message.

A SOAP Fault is returned to a service reference as an exception of type FaultException. So you will never see a SoapException.

John Saunders
  • 160,644
  • 26
  • 247
  • 397