前言:
WCF异常类型:
WCF客户端异常处理实例:
ICalculator.cs代码如下:
class="code_img_closed" src="/Upload/Images/2015041110/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('88afa3a7-4a63-46ec-9f1a-1a28da1fbe67',event)" src="/Upload/Images/2015041110/2B1B950FA3DF188F.gif" alt="" />using System.ServiceModel; using System.Collections.Generic; using System.Runtime.Serialization; namespace Service { [ServiceContract] public interface ICalculator { [OperationContract] int Add(int value1, int value2); [OperationContract] int Divide(int value1, int value2); } }View Code
Calculator.cs代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace Service { public class Calculator:ICalculator { public int Add(int value1, int value2) { return value1 + value2; } public int Divide(int value1, int value2) { try { return value1 / value2; } catch(DivideByZeroException) { throw new FaultException("除数不能为0"); } } } }View Code
2. Host:控制台应用程序。用来承载服务,添加对于Service程序集的引用后,实现以下代码就可以承载服务。
Program.cs的代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Service; using System.ServiceModel; namespace Host { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(Calculator))) { host.Opened += delegate { Console.WriteLine("服务已经启动,按任意键终止!"); }; host.Open(); Console.Read(); } } } }View Code
App.config的代码如下:
<?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service name="Service.Calculator" behaviorConfiguration="mexBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:1234/Calculator/"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="Service.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="mexBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>View Code
3. Client:控制台应用程序。将Host承载服务启动后,客户端程序添加对服务地址http://localhost:1234/Calculator/的引用,将命名空间设置为CalculatorServiceRef,
接下来我们就可以调用服务呢。Client的Program.cs代码如下:
首先,我们将2、3的代码注释掉,只验证服务异常抛出的结果,我们把Divide的除数设置为0,此时应该会捕获到服务端抛出的异常信息。运行结果如下:
然后,我们把1、3注释,只验证通讯超时的异常抛出。我们将通道连接后的操作时间设置为非常小的一个值,那么服务端的运算肯定来不及处理,就会抛出超
时的异常信息。运行结果如下:
最后,我们将1、2注释,只验证通讯错误异常信息,我们在客户端执行完Add()后,就把服务终止,即服务终止连接则会抛出通讯错误的异常信息,运行结果如下所示:
总结:
如果此属性仍然处于打开状态,则客户端仍然可以使用。否则,则应中止客户端并释放对其的所有引用。具体参照代码如下:
if (proxy.State == CommunicationState.Opened){ Console.WriteLine("CommunicationState is Opened"); }