Capturing SoapException thrown by WebService

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 the basic application for checking it (one button calls the Test method on a 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 would like to catch the SoapException thrown by my WebService, but I always go to the catch FaultException block, getting this as a message:

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

How can I catch a real SoapException and not a FaultException ? Something I missed in the WebService?

+6
c # exception try-catch asmx
source share
2 answers

I think the main β€œproblem” is that you are using a WCF service link that connects to the ASP.NET web service (.asmx).

The β€œeasiest” way to handle this is probably to use a web link instead of a WCF service link on the client. You do this by selecting the Advanced button at the bottom of the Add Service dialog box, and then the Add Web Link button at the bottom of this screen. I believe using a web link should give you a SoapException.

The correct way (if you want to follow Microsoft's recommendations) is to publish the WCF service instead of the .asmx service. This is a whole other chapter, though ..

+7
source share

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

A SOAP error is returned to the service link as an exception of type FaultException . This way you will never see a SoapException .

+5
source share

All Articles