.net Web服务异常处理

.net Web服务异常处理,.net,exception-handling,web-services,.net,Exception Handling,Web Services,我有一个使用C#Webservice的Winforms应用程序。 如果Web服务抛出异常,我的客户端应用程序总是会得到一个SoapException,而不是“真正的”异常 下面是一个演示: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] pu

我有一个使用C#Webservice的Winforms应用程序。 如果Web服务抛出异常,我的客户端应用程序总是会得到一个SoapException,而不是“真正的”异常

下面是一个演示:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        throw new IndexOutOfRangeException("just a demo exception");
    }
}
现在,在客户端,我希望能够以不同的方式处理不同的异常

        try
        {
            ServiceReference1.Service1SoapClient client
                = new ServiceReference1.Service1SoapClient();
            Button1.Text = client.HelloWorld();
        }
        catch (IndexOutOfRangeException ex)
        {
            // I know how to handle IndexOutOfRangeException
            // but this block is never reached
        }
        catch (MyOwnException ex)
        {
            // I know how to handle MyOwnException
            // but this block is never reached
        }
        catch (System.ServiceModel.FaultException ex)
        {
            // I always end in this block
        }
但这不起作用,因为我总是得到一个“System.ServiceModel.FaultException”,我只能通过解析异常的消息属性来找出“真正的”异常:

        System.Web.Services.Protocols.SoapException: Server was unable
        to process request. ---> System.IndexOutOfRangeException: just a demo\n
           at SoapExceptionTest.Service1.Service1.HelloWorld() in ...
        --- End of inner exception stack trace ---

有什么方法可以让它以某种方式工作吗?

根据我的经验,web服务将在响应中返回序列化的异常。然后由客户机反序列化它们并采取适当的操作


快速的谷歌搜索发现了这一点:

您应该记住,SOAP不知道.NET异常,web服务中的错误会作为错误返回。您应该考虑设计Web服务,以便它们捕获错误并返回错误信息作为响应的一部分,并且您的客户端代码处理该错误。或者,yu可以使用SOAP故障机制

这篇古老但有用的MSDN文章可能会对您有所帮助