Catching a custom Exception thrown by a WebMethod on ASP.NET WebService

后端 未结 1 1455
庸人自扰
庸人自扰 2021-02-15 19:21

I have a classical asp.net web service (asmx) and a web method in it. I need to throw a custom exception for some case in my web method, and I need to catch that specific custom

1条回答
  •  别跟我提以往
    2021-02-15 19:55

    ASP.NET Web Service can throw any type of exception: SoapException, HelloWorldException or soever. However, the exception is serialized into a SOAP Fault element, and regardless of the type of the exception thrown in the service, the exception is converted into a SoapException while deserialization. Hence, it is not possible to catch the HelloWorldException with my catch block in my question, even if I deploy the HelloWorldException to the client.

    For an ASP.NET client, the only way is to catch the exception as SoapException and handle it by its Actor or SoapFaultSubCode property.

    I've basically solved my problem as below:

    Web Service:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        public HelloWorldOutput HelloWorld(HelloWorldInput input)
        {
            try
            {
                // My Code
                return new HelloWorldOutput();
            }
            catch (Exception ex)
            {
                throw new SoapException("Hello World Exception",   
                     SoapException.ServerFaultCode, "HelloWorld", ex);
            }
        }
    }
    

    Client:

    public static void Main()
    {
        WebService service = new WebService();
        try
        {
            service.HelloWorld(new HelloWorldInput());
        }
        catch (SoapException ex)
        {
            if(ex.Actor == "HelloWorld")
                // Do sth with HelloWorldException
        }
        catch (Exception ex)
        {
            // Do sth with Exception
        }
    }
    

    Together with the document which Bryce Fischer wrote in his answer; these msdn documents also has helpful information about throwing and handling web service exceptions.

    How to: Throw Exceptions from a Web Service Created Using ASP.NET

    How to: Handle Exceptions Thrown by a Web Service Method

    0 讨论(0)
提交回复
热议问题