问题
My web service method returns a collection object, this will serialize nicely, thanks to the way C# web services work!
But if my code throws an uncaught exception, I want to instead return a custom error object.
Is this possible using 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>
回答1:
Yes, this is possible.
What you'll need to look into is the SoapException class, and specifically the Detail property of the SoapException class.
The SoapException class will effectively render a "Soap Fault", which is the standards-compliant 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 can thus contain either a single node/element or a hierarchy of child nodes. The Detail node could therefore easily contain and act as the "parent" for the serialized representation of your own custom error object.
From MSDN:
The Detail property is intended for supplying application specific error details related to the Body element of the SOAP request. According to the SOAP specification, if an an error occurrs because the client request could not be processed due to the Body element of the SOAP request, the Detail property must be set. If an error occured in the header entries of the SOAP request, you must throw a SoapHeaderException, so that the error details are returned in the SOAP header. If the error did not occur, due to the processing of the Body element, then the Detail property must not be set.
In building an XmlNode for the Detail property, the Name and Namespace properties of DetailElementName can be used to ensure consistancy [sic] with the SOAP specification.
All immediate child elements of the detail element are called detail entries and each detail entry is encoded as an independent element within the detail element.
Note that if you wish to remain correctly SOAP compliant with your web service responses, you'll need to return a SoapHeaderException rather than a SoapException if the error occurs within the client's header section of the original XML request (this can often be the case when using custom SOAP headers for e.g. security credentials) as detailed above.
来源:https://stackoverflow.com/questions/1153710/how-to-return-errors-from-an-asmx-web-service