use*_*417 5 wcf servicebehavior ierrorhandler
我在为WCF服务配置ServiceBehavior时遇到问题.
一些背景.基本上我正在开发一个应该在IIS上运行的REST服务WCF.我需要能够记录服务抛出的异常(我正在使用log4net)并根据异常类型返回HTTP状态代码.我希望我的服务实现对WCF相关的东西知之甚少,所以我不想在服务的每个地方将异常转换为FaultException.所以我发现将自己的IErrorHandler添加到服务主机是最好的方法.
我的问题是,无论我尝试什么,我似乎无法在Web.config中获得我的自定义ServiceBehavior的配置.这是相关的代码.
网络配置.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="UsingErrorLogBehavior">
<errorLogBehavior/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="errorLogBehavior"
type="MyNameSpace.Web.ErrorExtensionElement, MyNameSpace.Web"/>
</behaviorExtensions>
</extensions>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="false"
defaultOutgoingResponseFormat="Json"
maxReceivedMessageSize="4194304" transferMode="Buffered" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)
ErrorExtensionElement.
namespace MyNameSpace.Web
{
public class ErrorExtensionElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof(ErrorServiceBehavior); }
}
protected override object CreateBehavior()
{
return new ErrorServiceBehavior();
}
}
}
Run Code Online (Sandbox Code Playgroud)
ErrorServiceBehavior.
namespace MyNameSpace.Web
{
public class ErrorServiceBehavior : IServiceBehavior
{
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
{
channelDispatcher.ErrorHandlers.Add(new ExceptionModule());
}
}
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
ExceptionModule实现IErrorHandler的位置.
您有一个<serviceBehavior>名为“UsingErrorLogBehavior”的部分,但没有服务配置引用该部分。您可以将该部分设置为默认服务行为(通过不为其指定名称,就像端点行为一样),或者<service>为引用该行为的服务添加一个元素:
<services>
<service name="YourNamespace.YourServiceName"
behaviorConfiguration="UsingErrorLogBehavior">
<endpoint address=""
binding="webHttpBinding"
contract="YourNamespace.YourContractName" />
</service>
</services>
Run Code Online (Sandbox Code Playgroud)