How to Return Errors from an ASMX Web Service?

后端 未结 1 1793
迷失自我
迷失自我 2021-01-12 22:29

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

相关标签:
1条回答
  • 2021-01-12 23:04

    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.

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