加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从ASMX Web服务捕获自定义异常

发布时间:2020-12-15 03:51:34 所属栏目:百科 来源:网络整理
导读:我有一个Web服务,我已经创建了一个自定义异常.假设这个异常的名字是InvalidContractException. 我想做的是如果一个特定的步骤发生,我想抛出这个异常.但是,我无法弄清楚客户端如何捕获InvalidContractException以便正确处理它. 这是一个用C#编写的ASP.Net Web
我有一个Web服务,我已经创建了一个自定义异常.假设这个异常的名字是InvalidContractException.

我想做的是如果一个特定的步骤发生,我想抛出这个异常.但是,我无法弄清楚客户端如何捕获InvalidContractException以便正确处理它.

这是一个用C#编写的ASP.Net Web服务

解决方法

你不能这样做:

> Web服务执行SOAP故障.异常是平台特定的.
>当ASMX Web服务中未处理异常时,.NET会将其转换为SOAP Fault.异常的细节不是序列化的.
>在ASMX客户端中,SOAP故障将被转换为SoapException.

ASMX Web服务对SOAP故障没有适当的支持.除了客户端的SoapException之外,没有办法获得任何异常.

升级到WCF的另一个原因.

作为您不能使用ASMX的一个例子,以下是WCF的工作原理. WCF允许您为每个Web服务操作指定哪些故障可以返回:

[ServiceContract]
public interface IMyServiceContract
{
    [FaultContract(typeof(IntegerZeroFault))]
    [FaultContract(typeof(SomeOtherFault))]
    [OperationContract]
    public string GetSomeString(int someInteger);
}

[DataContract]
public class IntegerZeroFault
{
    [DataMember]
    public string WhichInteger {get;set;}
}

[DataContract]
public class SomeOtherFault
{
    [DataMember]
    public string ErrorMessage {get;set;}
}

public class MyService : IMyServiceContract
{
    public string GetSomeString(int someInteger)
    {
        if (someInteger == 0) 
            throw new FaultException<IntegerZeroFault>(
                new IntegerZeroFault{WhichInteger="someInteger"});
        if (someInteger != 42)
            throw new FaultException<SomeOtherFault>(
                new SomeOtherFault{ErrorMessage ="That's not the anaswer"});
        return "Don't panic";
    }
}

然后,WCF客户机可以捕获例如FaultException< SomeOtherFault>.当我使用Java客户端尝试过这个问题时,它可以捕获IBM Rational Web Developer创建的SomeOtherFault来从Java Exception类派生.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读