Using IExceptionLogger with per-controller IControllerConfiguration in WebApi

Using IExceptionLogger with per-controller IControllerConfiguration in WebApi

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.

Author

Shannon Thompson

I'm a Senior Software Engineer working full time at Microsoft. Previously, I was working at Umbraco HQ for about 10 years. I maintain several open source projects (many related to Umbraco) such as Articulate, Examine and Smidge, and I also have a commercial software offering called ExamineX. Welcome to my blog :)

comments powered by Disqus