Global handler for setting 404 error code

Topics: Web Api
Jun 30, 2011 at 11:34 PM
Edited Jun 30, 2011 at 11:37 PM

Hi there,

I've been meaning to create a global handler which sets the HttpStatusCode to 404 whenever a null object is returned.

What I have so far is a NullResultHandler class:

public class NullResultHandler : HttpOperationHandler<HttpResponseMessage, HttpResponseMessage>
	public NullResultHandler() : base("response")
	public override HttpResponseMessage OnHandle(HttpResponseMessage input)
		if (input.Content == null)
			input.StatusCode = System.Net.HttpStatusCode.NotFound;
		return input;

And I register it in global.asax.cs as such:

Action<Collection<HttpOperationHandler>> handlers = c => c.Add(new NullResultHandler());
var config = HttpHostConfiguration.Create()
	.SetResourceFactory(new NinjectResourceFactory(kernel))
	.AddResponseHandlers(handlers, (s, o) => true);
routes.MapServiceRoute<ContactApi>("contact", config);

In ContactApi I have a method:

[WebGet(UriTemplate = "{id}")]
public Contact Get(int id)
	return _contactRepository.Get(id);

The handler is triggered but the problem is that "input.Content" is never null, but an instance of type: Microsoft.ApplicationServer.Http.ObjectContent<ContactManager.Resources.Contact>

I tried with input.Content.ReadAs(Type type) but then I get errors like: No 'MediaTypeFormatter' is available to read an object of type 'Object' with the media type ''undefined''.

How do I get to the actual value in the ObjectContent object?

Any help is appreciated !


Jul 1, 2011 at 7:17 PM

That's weird, I use this code to get the object value and it works whether the value is null or not

 dynamic content = response.Content;
 var resource = content.ReadAs();

It works for me both in DelegatingChannels and OperationHandlers...

Jul 1, 2011 at 7:29 PM

I think that ReadAs() only works when type is HttpResponseMessage<T>.

I also created a class like


public class NullResultHandler<T> : HttpOperationHandler<HttpResponseMessage<T>, HttpResponseMessage<T>>


It works but then I need to add it like this:

Action<Collection<HttpOperationHandler>> handlers = c => c.Add(new NullResultHandler<Contact>());

So, for each (base-) type I would need to add a seperate handler.

That doesn't seem like a good solution.