如何:在服务协定中声明错误How to: Declare Faults in Service Contracts

在托管代码中,出现错误条件时引发异常。In managed code, exceptions are thrown when error conditions occur. 但在 Windows Communication Foundation (WCF)应用程序中,服务协定通过在服务协定中声明 SOAP 错误来指定向客户端返回的错误信息。In Windows Communication Foundation (WCF) applications, however, service contracts specify what error information is returned to clients by declaring SOAP faults in the service contract. 有关异常和错误间关系的概述,请参阅在协定和服务中指定和处理错误For an overview of the relationship between exceptions and faults, see Specifying and Handling Faults in Contracts and Services.

创建指定 SOAP 错误的服务协定Create a service contract that specifies a SOAP fault

  1. 创建至少包含一个操作的服务协定。Create a service contract that contains at least one operation. 有关示例,请参见 如何:定义服务协定For an example, see How to: Define a Service Contract.

  2. 选择可以指定希望向客户端通知的错误条件的操作。Select an operation that can specify an error condition about which clients can expect to be notified. 若要确定哪些错误条件将 SOAP 错误返回给客户端,请参阅在协定和服务中指定和处理错误To decide which error conditions justify returning SOAP faults to clients, see Specifying and Handling Faults in Contracts and Services.

  3. 为所选操作应用 System.ServiceModel.FaultContractAttribute 并向构造函数传递可序列化错误类型。Apply a System.ServiceModel.FaultContractAttribute to the selected operation and pass a serializable fault type to the constructor. 有关创建和使用可序列化类型的详细信息,请参阅在服务协定中指定数据传输For details about creating and using serializable types, see Specifying Data Transfer in Service Contracts. 下面的示例演示如何指定 SampleMethod 操作可以产生 GreetingFaultThe following example shows how to specify that the SampleMethod operation can result in a GreetingFault.

    [OperationContract]
    [FaultContractAttribute(
      typeof(GreetingFault),
      Action="http://www.contoso.com/GreetingFault",
      ProtectionLevel=ProtectionLevel.EncryptAndSign
      )]
    string SampleMethod(string msg);
    
    <OperationContract, FaultContractAttribute(GetType(GreetingFault), Action:="http://www.contoso.com/GreetingFault", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
    Function SampleMethod(ByVal msg As String) As String
    
  4. 为向客户端传达错误条件的协定中的所有操作重复步骤 2 和步骤 3。Repeat steps 2 and 3 for all operations in the contract that communicate error conditions to clients.

实现返回指定 SOAP 错误的操作Implementing an Operation to Return a Specified SOAP Fault

操作指定可以返回特定 SOAP 错误(例如在前面的过程中)来向调用应用程序传达错误条件后,下一步就是实现该指定。Once an operation has specified that a specific SOAP fault can be returned (such as in the preceding procedure) to communicate an error condition to a calling application, the next step is to implement that specification.

在操作中引发指定的 SOAP 错误Throw the specified SOAP fault in the operation

  1. 当操作中出现 FaultContractAttribute 指定的错误条件时,将引发一个新的 System.ServiceModel.FaultException<TDetail>,其中指定的 SOAP 错误是类型参数。When a FaultContractAttribute-specified error condition occurs in an operation, throw a new System.ServiceModel.FaultException<TDetail> where the specified SOAP fault is the type parameter. 下面的示例演示如何在前面的过程和以下代码部分中显示的 GreetingFault 中引发 SampleMethodThe following example shows how to throw the GreetingFault in the SampleMethod shown in the preceding procedure and in the following Code section.

    throw new FaultException<GreetingFault>(new GreetingFault("A Greeting error occurred. You said: " + msg));
    
      Throw New FaultException(Of GreetingFault)(New GreetingFault("A Greeting error occurred. You said: " & msg))
    End If
    

示例Example

下面的代码示例演示为 GreetingFault 操作指定 SampleMethod 的单个操作的实现。The following code example shows an implementation of a single operation that specifies a GreetingFault for the SampleMethod operation.

using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(Namespace="http://microsoft.wcf.documentation")]
  public interface ISampleService{
    [OperationContract]
    [FaultContractAttribute(
      typeof(GreetingFault),
      Action="http://www.contoso.com/GreetingFault",
      ProtectionLevel=ProtectionLevel.EncryptAndSign
      )]
    string SampleMethod(string msg);
  }
 
  [DataContractAttribute]
  public class GreetingFault
  { 
    private string report;

    public GreetingFault(string message)
    {
      this.report = message;
    }

    [DataMemberAttribute]
    public string Message
    {
      get { return this.report; }
      set { this.report = value; }
    }
  }

  class SampleService : ISampleService
  {
  #region ISampleService Members

  public string  SampleMethod(string msg)
  {
    Console.WriteLine("Client said: " + msg);
    // Generate intermittent error behavior.
    Random rnd = new Random(DateTime.Now.Millisecond);
    int test = rnd.Next(5);
    if (test % 2 != 0)
      return "The service greets you: " + msg; 
    else
      throw new FaultException<GreetingFault>(new GreetingFault("A Greeting error occurred. You said: " + msg));
  }

  #endregion
  }
}

Imports System.Collections.Generic
Imports System.Net.Security
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation")> _
  Public Interface ISampleService
    <OperationContract, FaultContractAttribute(GetType(GreetingFault), Action:="http://www.contoso.com/GreetingFault", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
    Function SampleMethod(ByVal msg As String) As String
  End Interface

  <DataContractAttribute> _
  Public Class GreetingFault
    Private report As String

    Public Sub New(ByVal message As String)
      Me.report = message
    End Sub

    <DataMemberAttribute> _
    Public Property Message() As String
      Get
          Return Me.report
      End Get
      Set(ByVal value As String)
          Me.report = value
      End Set
    End Property
  End Class

  Friend Class SampleService
      Implements ISampleService
  #Region "ISampleService Members"

  Public Function SampleMethod(ByVal msg As String) As String Implements ISampleService.SampleMethod
    Console.WriteLine("Client said: " & msg)
    ' Generate intermittent error behavior.
    Dim rand As New Random(DateTime.Now.Millisecond)
    Dim test As Integer = rand.Next(5)
    If test Mod 2 <> 0 Then
      Return "The service greets you: " & msg
    Else
      Throw New FaultException(Of GreetingFault)(New GreetingFault("A Greeting error occurred. You said: " & msg))
    End If
  End Function

  #End Region
  End Class
End Namespace

请参阅See also