如何从 ASMX Web 服务返回错误?
我的 Web 服务方法返回一个集合对象,这将很好地序列化,这要归功于 C# Web 服务的工作方式!
但如果我的代码抛出未捕获的异常,我想返回一个自定义错误对象。
使用 C# ASP.NET v2 可以吗?
例如,
正常操作应返回:
<Books>
<book>Sample</book>
<book>Sample</book>
</Books>
但出现错误时我想要
<error>
<errorMessage></errorMessage>
</error>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是可能的。
您需要研究的是 SoapException 类,特别是 SoapException 类的详细属性。
SoapException 类将有效地呈现“Soap Fault”,这是符合标准的机制用于从 Web 服务方法向客户端/消费者返回错误信息。
SoapException 类的“Detail”属性的类型为 XmlNode 因此可以包含单个节点/元素或子节点的层次结构。 因此,详细信息节点可以轻松包含并充当您自己的自定义错误对象的序列化表示的“父级”。
来自 MSDN:
请注意,如果您希望 Web 服务响应保持正确的 SOAP 兼容性,则需要返回 SoapHeaderException 而不是 SoapException 如果 错误发生在原始 XML 请求的客户端标头部分中(通常情况下,使用自定义 SOAP 标头例如安全性凭据)如上所述。
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:
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.