FaultContractAttribute 클래스

정의

서비스 작업에서 처리 오류가 발생하는 경우 반환되는 SOAP 오류를 하나 이상 지정합니다.

public ref class FaultContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
public sealed class FaultContractAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true, Inherited=false)>]
type FaultContractAttribute = class
    inherit Attribute
Public NotInheritable Class FaultContractAttribute
Inherits Attribute
상속
FaultContractAttribute
특성

예제

다음 코드 예제에서는 작업의 세부 정보 형식GreetingFault이 있는 SOAP 오류를 반환할 수 있도록 SampleMethod 지정하는 데 사용하는 FaultContractAttribute 방법을 보여줍니다.

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

다음 코드 예제에서는 WCF 클라이언트가 ISampleService 이 SOAP 오류를 형식GreetingFault으로 경험하는 것을 FaultException<TDetail> 보여 줍니다.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.WCF.Documentation;

public class Client
{
  public static void Main()
  {
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient();
    try
    {
      // Making calls.
      Console.WriteLine("Enter the greeting to send: ");
      string greeting = Console.ReadLine();
      Console.WriteLine("The service responded: " + wcfClient.SampleMethod(greeting));

      Console.WriteLine("Press ENTER to exit:");
      Console.ReadLine();

      // Done with service.
      wcfClient.Close();
      Console.WriteLine("Done!");
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (FaultException<GreetingFault> greetingFault)
    {
      Console.WriteLine(greetingFault.Detail.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (FaultException unknownFault)
    {
      Console.WriteLine("An unknown exception was received. " + unknownFault.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message + commProblem.StackTrace);
      Console.ReadLine();
      wcfClient.Abort();
    }
  }
}

Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports Microsoft.WCF.Documentation

Public Class Client
  Public Shared Sub Main()
    ' Picks up configuration from the config file.
    Dim wcfClient As New SampleServiceClient()
    Try
      ' Making calls.
      Console.WriteLine("Enter the greeting to send: ")
      Dim greeting As String = Console.ReadLine()
      Console.WriteLine("The service responded: " & wcfClient.SampleMethod(greeting))

      Console.WriteLine("Press ENTER to exit:")
      Console.ReadLine()

      ' Done with service. 
      wcfClient.Close()
      Console.WriteLine("Done!")
    Catch timeProblem As TimeoutException
      Console.WriteLine("The service operation timed out. " & timeProblem.Message)
      Console.ReadLine()
      wcfClient.Abort()
    Catch greetingFault As FaultException(Of GreetingFault)
      Console.WriteLine(greetingFault.Detail.Message)
      Console.ReadLine()
      wcfClient.Abort()
    Catch unknownFault As FaultException
      Console.WriteLine("An unknown exception was received. " & unknownFault.Message)
      Console.ReadLine()
      wcfClient.Abort()
    Catch commProblem As CommunicationException
      Console.WriteLine("There was a communication problem. " & commProblem.Message + commProblem.StackTrace)
      Console.ReadLine()
      wcfClient.Abort()
    End Try
  End Sub
End Class

설명

작업에서 FaultContractAttribute 반환된 명시적 SOAP 오류 메시지로 서비스 작업의 WSDL(웹 서비스 설명 언어) 설명에 추가된 하나 이상의 특정 예외 조건을 선언하는 특성을 사용하여 작업을 표시합니다.

관리되는 모든 애플리케이션에서 처리 오류는 Exception 개체로 표시됩니다. SOAP 기반 애플리케이션에서 Windows Communication Foundation (WCF) 애플리케이션과 같은 서비스 메서드에 SOAP 오류 메시지를 사용 하 여 처리 오류 정보를 전달 합니다. WCF 애플리케이션 두 가지 유형의 오류 시스템에서 실행 되므로 클라이언트로 전송 해야 하는 모든 관리 되는 예외 정보는 예외에서 SOAP 오류로 변환 되어야 합니다. 기본 서비스 예외 동작을 사용하거나 예외가 오류 메시지에 매핑되는지 여부와 방법을 명시적으로 제어할 수 있습니다. 예외 및 WCF 애플리케이션에서 SOAP 결함의 개요를 보려면 지정 및 계약 및 서비스에서 오류 처리합니다.

서비스 작업은 클라이언트가 정상적인 작업 과정에서 수신할 것으로 예상할 수 있는 모든 SOAP 오류를 공식적으로 지정하는 데 사용하는 FaultContractAttribute 것이 좋습니다. 또한 정보 공개를 최소화하기 위해 클라이언트가 알아야 하는 정보만 SOAP 오류로 반환하는 것이 좋습니다.

  • 속성은 Action 오류 메시지의 동작을 제어합니다.

  • 이 속성은 DetailType 오류 메시지에서 serialize된 세부 정보 개체의 형식을 가져옵니다.

  • Namespace 속성은 Name 각각 오류 메시지의 이름과 네임스페이스를 제어합니다.

  • 오류 HasProtectionLevel 메시지에 보호 수준이 지정되어 있는지 여부를 나타내며, 이 ProtectionLevel 경우 속성이 해당 보호 수준을 제어합니다.

주의

오류 메시지에 중요한 정보가 전달되거나 보안 문제가 발생할 수 있는 경우 속성을 설정하는 것이 ProtectionLevel 좋습니다.

많은 시나리오에서 오류 메시지로 EncryptAndSign 설정하는 ProtectionLevel 것으로 충분합니다. 자세한 내용은 보호 수준 이해를 참조하세요.

표시된 FaultContractAttributeFaultException<TDetail> 작업에서 지정된 오류를 반환하려면 작업 중에 관리되는 예외가 발생할 때 형식 매개 변수가 serialize 가능한 오류 정보인 경우 throw합니다. 즉, 클라이언트 구현에서 throw 된 동일한 형식으로 SOAP 오류는 WCF 클라이언트 애플리케이션 화면으로 FaultException<TDetail> (여기서는 typeparameter은 직렬화 오류 정보). 양방향 FaultContractAttribute 서비스 작업 및 비동기 작업 쌍에 대해 SOAP 오류를 지정하는 데만 사용할 수 있습니다. 단방향 작업은 SOAP 오류를 지원하지 않으므로 지원하지 FaultContractAttribute않습니다.

참고

직렬화 가능한 모든 형식을 사용하여 오류 정보를 전달할 수 있습니다. 이 버전의 WCF에서 유일한 제한 사항은 a에 FaultContractAttribute 지정된 형식을 .으로 serialize할 수 System.Runtime.Serialization.DataContractSerializer있어야 한다는 것입니다. 제공된 serialization 지원에 DataContractSerializer 대해서는 데이터 계약 직렬 변환기를 참조하세요.

예를 들어 클라이언트가 서비스 메서드의 형식 매개 변수 FaultContractAttribute 를 포함하는 Int32SOAP 오류를 예상할 수 있도록 지정합니다.

참고

다음 코드 예제에서는 , Name또는 Namespace 속성을 설정 ProtectionLevel하지 않습니다.

[OperationContractAttribute]
[FaultContractAttribute(typeof(int))]
int Divide(int arg1, int arg2);
  <OperationContractAttribute(), FaultContractAttribute(GetType(Integer))> _
    Function Divide(ByVal arg1 As Integer, ByVal arg2 As Integer) As Integer
End Interface 'FCADemonstration

그런 다음 서비스 메서드에서 형식 매개 변수가 오류 정보를 포함하는 형식인 새 FaultException<TDetail> 형식을 throw합니다(위의 경우) Int32. 예를 들면 다음과 같습니다.

throw new FaultException<int>(4);
Throw New FaultException(Of Integer)(4)

앞의 예제는 매우 기본입니다. 코드를 사용하여 System.Int32 거의 모든 정보를 전달할 수 있으므로 이 세부 정보 형식은 가장 유용하지 않습니다. 일반적으로 WCF 애플리케이션 특정 클라이언트의 오류 정보 요구 사항과 세부 유형과 SOAP 오류를 지정합니다. 자세한 예제는 예제 섹션을 참조하세요.

참고

형식 매개 변수가 FaultException<TDetail>System.String을 지정하면 문자열 값이 클라이언트 애플리케이션의 Detail 속성에 할당되므로 클라이언트가 FaultException<TDetail>.ToString 메서드를 호출하여 해당 문자열을 가져올 수 없습니다. 클라이언트 애플리케이션이 Exception.ToString을 호출할 때 문자열 값이 반환되도록 하려면 작업 내에서 System.ServiceModel.FaultException 예외를 throw하고 문자열을 생성자에 전달합니다.

예외 또는 FaultException<TDetail>이 throw될 때 애플리케이션의 동작을 명시적으로 제어하려면 System.ServiceModel.Dispatcher.IErrorHandler, System.ServiceModel.Description.IServiceBehavior 또는 System.ServiceModel.Description.IContractBehavior에서 System.ServiceModel.Description.IEndpointBehavior 인터페이스를 구현하고 이 인터페이스를 ChannelDispatcher.ErrorHandlers 속성에 할당합니다. IErrorHandler 를 사용하면 생성된 SOAP 오류를 명시적으로 제어하고 클라이언트로 다시 보낼지 여부를 제어할 수 있습니다.

디버깅을 위해 설정 합니다 ServiceBehaviorAttribute.IncludeExceptionDetailInFaultstrue 코드에 사용할 수는 ServiceDebugBehavior.IncludeExceptionDetailInFaults 애플리케이션 구성 파일에서. 사용하도록 설정하면 서비스는 자동으로 예외 정보를 호출자에게 반환합니다. 이러한 오류는 클라이언트에 예외로 FaultException 표시됩니다.

중요

관리 되는 예외는 내부 애플리케이션 정보를 노출할 수, 있으므로 설정 ServiceBehaviorAttribute.IncludeExceptionDetailInFaultsServiceDebugBehavior.IncludeExceptionDetailInFaultstrue WCF 클라이언트에서는 개인적으로 포함 하 여 내부 서비스 작업 예외에 대 한 정보를 허용 하려면 식별할 수 있는 정보나 기타 중요 한 정보입니다.

그러므로 임시로 서비스 애플리케이션을 디버깅하려는 경우 권장되는 유일한 방법은 ServiceBehaviorAttribute.IncludeExceptionDetailInFaults 또는 ServiceDebugBehavior.IncludeExceptionDetailInFaultstrue로 설정하는 것입니다. 또한 이 방법으로 처리되지 않은 관리되는 예외를 반환하는 메서드의 WSDL에는 FaultException<TDetail> 형식의 String에 대한 계약이 포함되지 않습니다. 클라이언트는 디버깅 정보를 제대로 가져오려면 알 수 없는 SOAP 오류(WCF 클라이언트에 개체로 System.ServiceModel.FaultException 반환됨)가 발생할 수 있습니다.

생성자

FaultContractAttribute(Type)

FaultContractAttribute 클래스의 새 인스턴스를 초기화합니다.

속성

Action

작업 계약의 일부로 지정된 SOAP 오류 메시지의 동작을 가져오거나 설정합니다.

DetailType

오류 정보가 포함된 serialize할 수 있는 개체의 형식을 가져옵니다.

HasProtectionLevel

SOAP 오류 메시지에 보호 수준이 할당되어 있는지 여부를 나타내는 값을 가져옵니다.

Name

WSDL(웹 서비스 기술 언어)에서 오류 메시지의 이름을 가져오거나 설정합니다.

Namespace

SOAP 오류의 네임스페이스를 가져오거나 설정합니다.

ProtectionLevel

바인딩에서 SOAP 오류에 필요한 보호 수준을 지정합니다.

TypeId

파생 클래스에서 구현된 경우 이 Attribute에 대한 고유 식별자를 가져옵니다.

(다음에서 상속됨 Attribute)

메서드

Equals(Object)

이 인스턴스가 지정된 개체와 같은지를 나타내는 값을 반환합니다.

(다음에서 상속됨 Attribute)
GetHashCode()

이 인스턴스의 해시 코드를 반환합니다.

(다음에서 상속됨 Attribute)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
IsDefaultAttribute()

파생 클래스에서 재정의된 경우 이 인스턴스 값이 파생 클래스에 대한 기본값인지 여부를 표시합니다.

(다음에서 상속됨 Attribute)
Match(Object)

파생 클래스에서 재정의된 경우 이 인스턴스가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다.

(다음에서 상속됨 Attribute)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

명시적 인터페이스 구현

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

이름 집합을 해당하는 디스패치 식별자 집합에 매핑합니다.

(다음에서 상속됨 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

인터페이스의 형식 정보를 가져오는 데 사용할 수 있는 개체의 형식 정보를 검색합니다.

(다음에서 상속됨 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

개체에서 제공하는 형식 정보 인터페이스의 수를 검색합니다(0 또는 1).

(다음에서 상속됨 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

개체에서 노출하는 메서드와 속성에 대한 액세스를 제공합니다.

(다음에서 상속됨 Attribute)

적용 대상