bạn có thể thực hiện, nhưng có lẽ sẽ tốt hơn nếu triển khai IErrorHandler và add it as a behaviour vào dịch vụ của bạn, điều này sẽ cho phép xử lý ngoại lệ của bạn ở một nơi duy nhất. có thể tạo lỗi ngoại lệ ở đó để trả lại chi tiết cho người dùng.
ErrorHandler : IErrorHandler
{
... just implement the handling of errors here, however you want to handle them
}
sau đó để tạo ra một hành vi trong đó sử dụng này:
/// <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
}
Sau đó, nếu bạn đang tự lưu trữ bạn chỉ có thể thêm các hành vi lập trình:
myServiceHost.Description.Behaviors.Add (new ErrorHandlerBehavior());
nếu bạn muốn thêm nó thông qua cấu hình thì bạn cần một trong những điều sau:
public class ErrorHandlerElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof (ErrorHandlerBehavior); }
}
protected override object CreateBehavior()
{
return new ErrorHandlerBehavior();
}
}
}
và sau đó cấu hình:
<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>
Nguồn
2012-04-23 22:08:19
Hey Sam, bất kỳ cơ hội của một mã ví dụ trong câu trả lời của bạn? – EtherDragon
@EtherDragon ví dụ được liên kết cho biết cách thêm hành vi theo chương trình. –
@AbuHamzah, đã cập nhật và thêm ví dụ –