gpt4 book ai didi

wcf - 如何在 wcf rest 服务中添加全局错误处理

转载 作者:行者123 更新时间:2023-12-04 21:13:59 25 4
gpt4 key购买 nike

在我的网络应用程序中,我使用 global.asax 中的 Application_Error 函数来记录所有异常,如下所示:

void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();

while (ex.GetBaseException() != null)
{
ex = ex.GetBaseException();
}

log.writeError(ex.ToString());
}

我在 WCF REST 服务中尝试过类似的方法,但没有成功。我将如何添加全局错误处理?我看到了this article ,但我是 IServiceBehavior 的新手。我应该在哪里添加上面的代码?

最佳答案

我使用:

1) AppDomain.CurrentDomain.UnhandledException 事件

2) TaskScheduler.UnobservedTaskException 事件

3) IErrorHandler:

    public class ErrorHandler : IErrorHandler
{
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
var faultException = new FaultException<string>("Server error: " + error.Format());
var messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, null);
}

public bool HandleError(Exception error)
{
return false;
//return true; //if handled
}
}

[AttributeUsage(AttributeTargets.Class)]
public class ErrorHandlerBehavior : Attribute, IEndpointBehavior, IServiceBehavior
{
public void Validate(ServiceEndpoint endpoint)
{

}

public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{

}

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandler());
}

public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{

}

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)
{
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
{
channelDispatcher.ErrorHandlers.Add(new ErrorHandler());
}
}
}

这可以应用于整个服务实现。类:

[ErrorHandlerBehavior]
public class SubscriberInfoTaskService : {}

或端点:

var endpoint = Host.Description.Endpoints.FirstOrDefault();

//foreach (ChannelDispatcher channelDispatcher in Host.ChannelDispatchers) //ChannelDispatcherBase
//{
// channelDispatcher.ErrorHandlers.Add(new ErrorHandler());
//}

endpoint.Behaviors.Add(new ErrorHandlerBehavior());

这里是关于使用配置的:http://www.steverb.com/post/2008/11/24/Useful-WCF-Behaviors-IErrorHandler.aspx

关于wcf - 如何在 wcf rest 服务中添加全局错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15126788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com