你可以做,但它可能會更好地執行IErrorHandler和add it as a behaviour爲您服務,讓您的未處理的異常在一個地方進行處理,所以你能夠在那裏創建一個故障異常來向用戶返回詳細信息。
ErrorHandler : IErrorHandler
{
... just implement the handling of errors here, however you want to handle them
}
然後創建一個使用此行爲:
/// <summary>
/// Custom WCF Behaviour for Service Level Exception handling.
/// </summary>
public class ErrorHandlerBehavior : IServiceBehavior
{
#region Implementation of IServiceBehavior
public void Validate (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void AddBindingParameters (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler = new ErrorHandler();
foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
var channelDispatcher = channelDispatcherBase as ChannelDispatcher;
if (channelDispatcher != null)
{
channelDispatcher.ErrorHandlers.Add (errorHandler);
}
}
}
#endregion
}
然後,如果你是自託管,你可以再補充程序的行爲:
myServiceHost.Description.Behaviors.Add (new ErrorHandlerBehavior());
,如果你想添加它通過配置,然後你需要其中的一個:
public class ErrorHandlerElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof (ErrorHandlerBehavior); }
}
protected override object CreateBehavior()
{
return new ErrorHandlerBehavior();
}
}
}
,然後配置:
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="ErrorLogging" type="ErrorHandlerBehavior, ErrorHandling, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<whatever>" />
</behaviorExtensions>
</extensions>
<bindings>
<basicHttpBinding>
<binding name="basicBinding">
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="Service1Behavior" name="Service">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Service" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service1Behavior">
<serviceMetadata httpGetUrl="" httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<ErrorLogging /> <--this adds the behaviour to the service behaviours -->
</behavior>
</serviceBehaviors>
</behaviors>
嘿山姆,在你的答案代碼示例的任何機會呢? – EtherDragon 2012-04-23 22:46:53
@EtherDragon鏈接的示例顯示如何以編程方式添加行爲。 – 2012-04-23 23:00:18
@AbuHamzah,更新並添加示例 – 2012-04-23 23:10:11