我如何提取一个SOAP异常在ASP.NET内部异常?异常、SOAP、NET、ASP

2023-09-02 02:01:38 作者:晚吟

我有这样一个简单的Web服务操作:

I have a simple web service operation like this one:

    [WebMethod]
    public string HelloWorld()
    {
        throw new Exception("HelloWorldException");
        return "Hello World";
    }

然后,我有一个消费Web服务客户端应用程序,然后调用运行。很显然,这会抛出异常: - )

And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception :-)

    try
    {
        hwservicens.Service1 service1 = new hwservicens.Service1();
        service1.HelloWorld();
    }
    catch(Exception e)
    {
        Console.WriteLine(e.ToString());
    }

在我追赶块,我想要做的就是提取实际的异常的消息把它用在我的code。抓住了唯一的例外是的SoapException ,这是很好的,但它的消息属性是这样的...

In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a SoapException, which is fine, but it's Message property is like this...

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: HelloWorldException
   at WebService1.Service1.HelloWorld() in C:svnrootVordurWebService1Service1.asmx.cs:line 27
   --- End of inner exception stack trace ---

...和的InnerException

我希望做的是提取消息的InnerException (即 HelloWorldException 文本),任何人都可以帮助吗?如果你能避免它,请不要认为解析消息的属性的SoapException

What I would like to do is extract the Message property of the InnerException (the HelloWorldException text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the Message property of the SoapException.

推荐答案

不幸的是,我不认为这是可能的。

Unfortunately I don't think this is possible.

你提出你的Web服务code中的例外是EN coded到一个SOAP错误,然后被作为字符串传递回客户端code。

The exception you are raising in your web service code is being encoded into a Soap Fault, which then being passed as a string back to your client code.

你们看到的的SoapException消息只是从SOAP错误,这是不被转换回一个异常的文字,而仅仅是存储为文本。

What you are seeing in the SoapException message is simply the text from the Soap fault, which is not being converted back to an exception, but merely stored as text.

如果您想返回的错误条件那么我建议从Web服务返回的自定义类的有用信息,可以有一个错误属性,其中包含您的信息。

If you want to return useful information in error conditions then I recommend returning a custom class from your web service which can have an "Error" property which contains your information.

[WebMethod]
public ResponseClass HelloWorld()
{
  ResponseClass c = new ResponseClass();
  try 
  {
    throw new Exception("Exception Text");
    // The following would be returned on a success
    c.WasError = false;
    c.ReturnValue = "Hello World";
  }
  catch(Exception e)
  {
    c.WasError = true;
    c.ErrorMessage = e.Message;
    return c;
  }
}