开发者

How to catch and log ASP.NET / WCF Bad requests errors?

I want to catch all "http 400 Bad request" errors that are sent to my WCF4 web service (REST) and currently all bad requests (perhaps error in the xml/json) is just redirected to the generic IIS 400 bad req开发者_如何学JAVAuest error page.

Neither the Application_Error in global.asax or the custom overriden 400 error page handler in IIS not called.

So are there any other way to catch errors in WCF?


I have been looking at this myself and the way in which I have sorted it is by making an implementation of the System.ServiceModel.Dispatcher.IErrorHandler:

public class EventLogErrorHandler : BehaviorExtensionElement, IErrorHandler, IServiceBehavior
{
    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var log = new EventLog("APPLICATION",Environment.MachineName, "SomeSourceName");
        log.WriteEntry("PROVIDING FAULT", EventLogEntryType.Information);
    }

    public bool HandleError(Exception error)
    {
        var log = new EventLog("APPLICATION", Environment.MachineName, "SomeSourceName");
        log.WriteEntry(error.ToString(), EventLogEntryType.Error);
        return true;
    }

    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 (var dispatcher in serviceHostBase.ChannelDispatchers)
            (dispatcher as ChannelDispatcher).ErrorHandlers.Add(this);
    }

    protected override object CreateBehavior()
    {
        return new EventLogErrorHandler();
    }

    public override Type BehaviorType
    {
        get { return GetType(); }
    }
}

I can then add this to the system.serviceModel tag inside the extensions tag like the following:

<extensions>
  <behaviorExtensions>
    <add name="errorhandler" type="SomeAssembly.SomeNamespace.EventLogErrorHandler, SomeAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  </behaviorExtensions>
</extensions>

The finally add this behavior to your service behaviours and when an error occurs of any sort you can put in the correct logic to handle as you see fit:

...
                <errorhandler />
            </behavior>
        </serviceBehaviors>
    </behaviors>

Hope this helps,

Andrew

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜