How to return errors from the ASMX web service?

My web service method returns a collection object, it will serialize nicely, thanks to how C # web services work!

But if my code throws an uncaught exception, I want to return my own error object instead.

Is this possible with C # ASP.NET v2?

For example,

Normal operation should return:

<Books> <book>Sample</book> <book>Sample</book> </Books> 

But on error I want

  <error> <errorMessage></errorMessage> </error> 
+6
c # web-services asmx soapfault
source share
1 answer

Yes it is possible.

What you need to study is the SoapException class , namely the Detailed property of the SoapException class.

The SoapException class will efficiently display a Soap Error , which is a standard-compatible mechanism for returning error information to clients / consumers from a web service method.

The Detail property of the SoapException class is of type XmlNode and therefore can contain either a single node / element or a hierarchy of child nodes. In this way, the node part can easily contain and act as a β€œparent” for the serialized representation of your own error object.

From MSDN:

The Detail property is intended to provide specific error information associated with the Body element of a SOAP request. According to the SOAP specification, if an error occurs because the client request cannot be processed due to the Body element of the SOAP request, the Detail property must be set. If an error occurs in the SOAP request header entries, you should throw a SoapHeaderException so that error data is returned in the SOAP header. If an error did not occur due to processing of the Body element, the Detail property should not be set.

When creating an XmlNode property for granularity, the Name and Namespace properties of the DetailElementName element can be used to ensure [sic] consistency using the SOAP specification.

All the immediate children of a part element are called detailed elements, and each record part is encoded as an independent element inside the detail element.

Note that if you want SOAP to match your web service responses, you need to return a SoapHeaderException rather than a SoapException if an error occurs in the client header section of the original XML request (this can often happen when using custom SOAP headers , e.g. security credentials) as described above.

+7
source share

All Articles