捕获WebService抛出的SoapException

时间:2011-02-15 15:05:47

标签: c# exception asmx try-catch soapexception

我写了以下服务:

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

一个测试它的基本应用程序(在click事件上调用Test方法的一个按钮):

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)
    {

    }
}

我想抓住我的WebService抛出的SoapException,但我总是转到FaultException catch块,得到消息:

  

System.Web.Services.Protocols.SoapException:message      在[...] WebService1 \ WebService1 \ Service1.asmx.cs中的WebService1.Service1.Test(String str):第25行

我怎样才能找到真实的SoapException,而不是FaultException? WebService中有什么我想念的吗?

2 个答案:

答案 0 :(得分:7)

我认为主要的“问题”是您正在使用连接到ASP.NET Web服务(.asmx)的WCF服务引用。

处理此问题的“最简单”方法可能是在客户端上使用Web引用而不是WCF服务引用。您可以通过选择“添加服务引用”对话框底部的“高级”按钮,然后选择该屏幕底部的“添加Web引用”来执行此操作。我相信使用Web Reference会给你一个SoapException。

正确的方法(如果您想遵循微软的建议)将发布WCF服务而不是.asmx服务。那是另一个章节。

答案 1 :(得分:5)

当ASMX服务抛出SoapException时,.NET将返回SOAP Fault消息。

SOAP Fault作为类型FaultException的异常返回给服务引用。所以你永远不会看到SoapException