我有一个经典的 asp.net web 服务 (asmx) 和一个 web 方法。我需要在我的 Web 方法中针对某些情况抛出自定义异常,并且我需要在调用 Web 服务方法时捕获该特定自定义异常。
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public HelloWorldOutput HelloWorld(HelloWorldInput input)
{
try
{
// My Code
return new HelloWorldOutput();
}
catch (Exception ex)
{
throw new HelloWorldException("Hello World Exception", ex);
}
}
}
作为示例的输入、输出和异常类:
public class HelloWorldInput { }
public class HelloWorldOutput { }
[Serializable]
public class HelloWorldException : Exception
{
public HelloWorldException() { }
public HelloWorldException(string message) : base(message) { }
public HelloWorldException(string message, Exception inner)
: base(message, inner) { }
protected HelloWorldException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
在客户端,我需要:
public static void Main()
{
WebService service = new WebService();
try
{
service.HelloWorld(new HelloWorldInput());
}
catch (HelloWorldException ex)
{
// Do sth with HelloWorldException
}
catch (Exception ex)
{
// Do sth with Exception
}
}
但是,我不能那样做,因为当我在客户端添加 Web 服务引用时,我有服务类、输入和输出类,但没有自定义异常类。
另外一个问题是,我在序列化 Exception 类时也有问题(因为 Exception.Data 属性实现了 IDictionary 接口(interface))
有没有办法以我的方式做到这一点,或者我的方式完全错误,还是我错过了网络服务基础知识的某些内容?
谢谢。
最佳答案
ASP.NET Web 服务可以抛出任何类型的异常:SoapException、HelloWorldException 等等。但是,异常被序列化为一个 SOAP Fault 元素,并且无论服务中抛出的异常类型如何,异常都会在反序列化时转换为 SoapException。因此,即使我将 HelloWorldException 部署到客户端,也无法使用问题中的 catch block 捕获 HelloWorldException。
对于 ASP.NET 客户端,唯一的方法是将异常捕获为 SoapException 并通过其 Actor
或 SoapFaultSubCode
属性进行处理。
我基本上解决了如下问题:
网络服务:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public HelloWorldOutput HelloWorld(HelloWorldInput input)
{
try
{
// My Code
return new HelloWorldOutput();
}
catch (Exception ex)
{
throw new SoapException("Hello World Exception",
SoapException.ServerFaultCode, "HelloWorld", ex);
}
}
}
客户:
public static void Main()
{
WebService service = new WebService();
try
{
service.HelloWorld(new HelloWorldInput());
}
catch (SoapException ex)
{
if(ex.Actor == "HelloWorld")
// Do sth with HelloWorldException
}
catch (Exception ex)
{
// Do sth with Exception
}
}
连同 Bryce Fischer 在他的回答中写的文件;这些 msdn 文档还包含有关抛出和处理 Web 服务异常的有用信息。
How to: Throw Exceptions from a Web Service Created Using ASP.NET
关于c# - 在 ASP.NET WebService 上捕获 WebMethod 抛出的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839317/