There’s plenty of examples online about implementing a custom IExceptionLogger globally in WebApi and I’m sure they all work as expected but what if you don’t want to register it globally? In that case you’d use an instance of IControllerConfiguration to do a “per-controller” configuration and in theory you could just use this syntax:


public class MyExceptionLoggerConfigurationAttribute : Attribute, IControllerConfiguration
{
	public virtual void Initialize(
		HttpControllerSettings controllerSettings, 
		HttpControllerDescriptor controllerDescriptor)
	{
		controllerSettings.Services.Add(
			typeof(IExceptionLogger), 
			new UnhandledExceptionLogger());
	}	
}

That seems pretty simple, and then you attribute whatever controller you want to use this new IExceptionLoggernope!

As it turns out, the custom UnhandledExceptionLogger instance will never get executed unless there is also an ExceptionFilter applied to the controller (even if it doesn’t do anything)! I can’t find documentation on this anywhere but it’s definitely the case. So to make the above work, we can just replace Attribute with ExceptionFilterAttribute like:


public class MyExceptionLoggerConfigurationAttribute : ExceptionFilterAttribute, IControllerConfiguration
{
	public virtual void Initialize(
		HttpControllerSettings controllerSettings, 
		HttpControllerDescriptor controllerDescriptor)
	{
		controllerSettings.Services.Add(
			typeof(IExceptionLogger), 
			new UnhandledExceptionLogger());
	}	
}

And voila! this works.