`

Exception Handling in WCF using Fault Contract

阅读更多

Introduction

In all managed applications, processing errors are represented by Exception objects. In WCF applications, service methods communicate processing error information using SOAP fault messages. SOAP faults are message types that are included in the metadata for a service operation and, therefore, create a fault contract that clients can use to make their operation more interactive. In addition, because SOAP faults are expressed to clients in XML form,theyare highly interoperable.

To be more concrete,let us start with anexample:

Create an empty solution in VS2005 called "IndigoException". Add one project called "IndigoService". Nexta dd a reference to System.ServiceModel and then a dd an interface.

using System;

using System.Collections.Generic;

using System.Text;

using System.ServiceModel;

using System.Runtime.Serialization;

namespace Indigo

{

[ServiceContract()]

public interface IService

{

[OperationContract]

[FaultContract(typeof (MyFaultException))]

string GetMessage();

}
}

Add one more class as follows:


using
System;

using System.Text;

using System.Runtime.Serialization;

namespace Indigo

{

[DataContract]

public class MyFaultException

{

private string _reason;

[DataMember]

public string Reason

{

get { return _reason; }

set { _reason = value ; }

}

}

}

Add one class "Service" and a reference to System.ServiceModel

using System;

using System.Collections.Generic;

using System.Text;

using System.ServiceModel;

namespace Indigo

{

public class Service : IService

{

#region IService Members

public string GetMessage()

{

try

{

int i, j, k;

j = 1;

k = 0;

i = j / k;

}

catch (Exception exp)

{

MyFaultException theFault = new MyFaultException();

theFault.Reason = "Some Error " + exp.Message.ToString();

throw new FaultException<MyFaultException>(theFault);

}

return "No Error" ;

}

#endregion

}

}

Build the project.

Now add another project "Host" and add reference to "IndigoService" project and to System.ServiceModel

using System;

using System.Collections.Generic;

using System.Text;

using System.ServiceModel;

namespace Indigo

{

class IndigoHost

{

internal static ServiceHost myServiceHost = null ;

static void Main(string [] args)

{

StartService();

Console .WriteLine("Service at your service" );

Console .ReadKey();

StopService();

}

internal static void StartService()

{

myServiceHost = new ServiceHost(typeof (Indigo.Service));

myServiceHost.Open();

}

internal static void StopService()

{

//Call StopService from your shutdown logic (i.e. dispose method)

if (myServiceHost.State != CommunicationState.Closed)

myServiceHost.Close();

}

}

}

Add app.config with the following XML:

<? xml version = "1.0 " encoding = "utf-8 " ?>

< configuration >

< system.serviceModel >

< services >

< service behaviorConfiguration = "MyServiceTypeBehaviors " name = "Indigo.Service ">

< endpoint address = "Service " binding = "wsHttpBinding " contract = "Indigo.IService " />

< host >

< baseAddresses >

< add baseAddress = "http://localhost:1111/Indigo " />

</ baseAddresses >

</ host >

</ service >

</ services >

< behaviors >

< serviceBehaviors >

< behavior name = "MyServiceTypeBehaviors ">

< serviceMetadata httpGetEnabled = "true " />

< serviceDebug includeExceptionDetailInFaults = "true " />

</ behavior >

</ serviceBehaviors >

</ behaviors >

</ system.serviceModel >
</ configuration >

Build the project. Run Host.exe from VS2005 command prompt. You should get the messageat thecommand prompt as follows:



Add another project "IndigoClient" and add System.ServiceModel

Now add service refrence to the service URL (i.e. http://localhost:1111/Indigo )

It will create localhost.cs in service reference.

Add a class Program.cs as follows:

using System;

using System.Collections.Generic;

using System.Text;

using System.ServiceModel;

namespace Indigo

{

class Program

{

static void Main(string [] args)

{

string result = "" ;

try

{

IndigoClient.localhost.IService ww = new IndigoClient.localhost.ServiceClient
();

result = ww.GetMessage();

}

catch (FaultException<IndigoClient.localhost.MyFaultException> ee)

{

result = "Exception: " + ee.Detail.Reason;

}

Console .WriteLine(result);

Console .ReadLine();

}

}

}


Add app.config with following XML


<?
xml version = "1.0 " encoding = "utf-8 " ?>

< configuration >

< system.serviceModel >

< bindings >

< wsHttpBinding >

< binding

分享到:
评论

相关推荐

    10.如何在WCF进行Exception Handling

    WCF 默认情况下会将所有未捕获的异常转换为一个“FaultException”,这可能导致客户端接收到不具体或不友好的错误信息。因此,了解如何在WCF中进行异常处理对于提升服务质量和用户体验至关重要。 一、异常类型与...

    具有FaultException详细信息的WCF DataContract

    标题中的“具有FaultException详细信息的WCF DataContract”指的是在Windows Communication Foundation (WCF)服务中使用DataContract和FaultException来处理错误信息的一种方法。WCF是.NET框架中用于构建跨平台、...

    restful host in wcf 源码

    本源码包"restful host in wcf"旨在帮助开发者理解如何在WCF中实现RESTful服务。 首先,我们需要了解WCF中的基本概念。WCF服务是由一个或多个终结点组成的,每个终结点包含地址、绑定和合同。地址定义了服务的位置...

    WCF基础入门学习资料

    对于初学者 会有帮助 契约  WCF所有的服务都是公开为契约,当你使用这个服务是就比约遵循一定的契约...错误契约(Fault Contract):定义抛出的错误。  4.消息契约(Message Contract):定义直接与服务交互的消息。

    WCF.Multi-Layer.Services.Development.with.Entity.Framework.4th.Edition

    Competence in Entity Framework will be needed to follow the examples in the book, but experience in creating WCF services using Entity Framework is not necessary. Developers and architects evaluating...

    WCF系列学习源码

    这涉及到WCF的错误处理机制,包括FaultException和CommunicationException的使用。 5. **WCF自定义通道**: 自定义通道是WCF中实现特定通信协议的关键。`WCF_自定义通道`展示了一个自定义通道的实现,这有助于理解...

    Synchronization Contexts in WCF

    在Windows Communication Foundation (WCF) 中,同步上下文(Synchronization Context)是一个关键概念,它涉及到服务操作的并发执行和线程模型。本篇文章将深入探讨这个主题,并结合实际示例来阐述其工作原理和重要...

    JS跨域调用WCF服务实例(WCF服务宿主到控制台)

    JavaScript(JS)与Windows Communication Foundation(WCF)服务之间的跨域调用是Web开发中常见的需求,尤其是在构建分布式系统和前后端分离的应用时。本文将详细介绍如何实现JS跨域调用WCF服务,并通过一个控制台...

    WCF服务简单实例WCF服务简单实例

    4. **处理异常**:WCF服务可能会抛出`FaultException`等异常,需要在客户端进行捕获和处理。 5. **关闭服务代理**:使用完毕后,记得关闭服务代理以释放资源。 **WCF服务的关键概念** - **服务契约(Service ...

    wcf 代理 wcf开发示例

    &lt;endpoint address="" binding="basicHttpBinding" contract="WcfService1.IService1" /&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; ``` 3. 客户端调用:在客户端...

    (精通WCF编程)Professional WCF Program.pdf(eng)

    8. **错误处理和异常**:WCF提供了一套完整的错误处理机制,包括FaultException和FaultContract,用于向客户端传达错误信息。 9. **服务行为和服务元数据**:服务行为控制服务的行为模式,如服务实例化、并发控制和...

    WCF秘籍(WCF必读圣经)

    programming in wcf english version editionprogramming in wcf english version editionprogramming in wcf english version editionprogramming in wcf english version edition

    WCF自定义异常

    当系统遇到无法处理的问题时,WCF会抛出异常,这些异常通常继承自`System.ServiceModel.CommunicationException`或`System.ServiceModel.FaultException`。然而,在某些情况下,开发者可能需要自定义异常来更好地...

    简单WCF调用的实现

    WCF支持异常处理,可以通过`FaultException`向客户端抛出错误信息。同时,使用`OperationContextScope`可以在服务端设置上下文,以便于追踪和调试。 ### 8. 配置文件 WCF服务和客户端通常使用配置文件(如`app....

    WCF错误异常demo

    当服务方法抛出未捕获的异常时,WCF默认会生成一个FaultException,将其转换为SOAP错误并返回给客户端。这种方式虽然简单,但可能不适用于所有情况,例如,我们可能希望提供更详细的错误信息,或者自定义错误格式。 ...

    WCF 聊天代码,wcf Duplex

    在WCF中,Duplex Contract是一种特殊的通信模式,它允许服务和客户端之间进行双向通信,就像电话通话一样,双方都能在任意时刻发送消息。本篇将深入讲解如何利用WCF Duplex实现一个简单的聊天功能。 首先,我们要...

Global site tag (gtag.js) - Google Analytics