Hopefully there are some WCF wizards out there that can spot my mistake here.
I am trying to set up a global error handler via an IErrorHandler based behaviorExtens
The issue here lies with the WCF Rest Starter Kit (which I didn't realize was in use since I didn't start this project), more specifically WebServiceHost2
. I opened the ServiceHost in Reflector and found this lovely little piece of code in OnOpening()
:
if (endpoint.Behaviors.Find<WebHttpBehavior>() != null)
{
endpoint.Behaviors.Remove<WebHttpBehavior>();
WebHttpBehavior2 item = new WebHttpBehavior2();
// other code omitted
endpoint.Behaviors.Add(item);
}
As you can see, no matter what behavior you want added to the endpoint, as long as it inherits from WebHttpBehavior the Rest Start Kit components will hijack your handler, remove it, and replace it with its own.
Keep in mind that WebHttpBehavior2 also inherits from WebHttBehavior so inheriting from WebHttpBehavior2 in my extension did nothing to help the matter.
The first step was to create a new WebSeriveHost that derived from WebServiceHost2
and overrode OnOpening()
and re-hijack what the Rest Starter Kit stole from me:
if(endpoint.Behaviors.Find<WebHttpBehavior>() != null)
{
endpoint.Behaviors.Remove<WebHttpBehavior>();
var item = ErrorBehavior();
// other code
endpoint.Behaviors.Add(item);
}
And then create a new WebServiceHostFactory that returned my custom WebServiceHost type.
Don't forget to set the ContentType of the response as well:
rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
Based on comments I would try to remove common webHttpBehavior. You have defined your own behavior derived from webHttp. There is no reason to have two webHttp behaviors in your service configuration. Moreover webHttp behavior adds its own error handler which behaves exactly as you describe. Maybe it will not help but you can give it a try.