向 WCF REST 服务添加全局错误处理 [英] Adding global error handling to WCF REST service
问题描述
我有一个 WCF/REST Web 服务,我正在尝试向其中添加全局异常处理程序.我正在标准 .NET 网站中寻找类似于 Application_Error 事件的内容.
I have a WCF/REST Web Service that I'm trying to add a global exception handler to. I'm looking for something similar to the Application_Error event in a standard .NET website.
我发现了很多关于使用 IErrorHandler 和 IServiceBehavior 的信息,例如这里详述的内容:http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx#Y1479
I've found lots of info about using IErrorHandler and IServiceBehavior like what's detailed here: http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx#Y1479
这似乎是我所需要的,但我发现的每个示例都假定该服务是在 web.config 中定义的.我没有这样做 - 我正在使用 RouteTables,在 global.asax 中配置,如下所示:
That seems like what I need, but every example I've found assumes that the service is defined in the web.config. I'm not doing that - I'm using RouteTables, configured in the global.asax, like so:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHost2Factory(), typeof(myService)));
}
那么,既然如此,我该如何配置我的自定义 IErrorHandler 和 IServiceBehavior?鉴于我使用的是 RouteTable 而不是通过 web.config 配置它,我是否走在正确的轨道上?我对 WCF 很陌生....
So, given that, how do I configure my custom IErrorHandler and IServiceBehavior? Am I even on the right track, given that I'm using a RouteTable rather than configuring it via the web.config? I'm very new to WCF....
推荐答案
IServiceBehaviour
的连接可以通过创建覆盖 的自定义
.WebServiceHostFactory
来实现CreateServiceHost
The wiring up of your IServiceBehaviour
can be achieved by creating a custom WebServiceHostFactory
that overrides CreateServiceHost
.
例如,如果您有一个实现 IServiceBehavior
的类 GlobalErrorHandlerBehaviour
,那么您可以按如下方式连接它:
For example if you have a class GlobalErrorHandlerBehaviour
which implements IServiceBehavior
, then you could wire it up as follows:
public class CustomWebServiceHostFactory : WebServiceHostFactory
{
protected override ServiceHost CreateServiceHost(System.Type serviceType, System.Uri[] baseAddresses)
{
return ApplyGlobalErrorHandler(base.CreateServiceHost(serviceType, baseAddresses));
}
private ServiceHost ApplyGlobalErrorHandler(ServiceHost serviceHost)
{
serviceHost.Description.Behaviors.Add(new GlobalErrorHandlerBehaviour());
return serviceHost;
}
}
然后,您将更新对 ServiceRoute
构造函数的调用以传入此自定义工厂.
You would then update your call to the ServiceRoute
constructor to pass in this custom factory.
这篇关于向 WCF REST 服务添加全局错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!