Global handler for setting 404 error code

Topics: Web Api
Jul 1, 2011 at 12:34 AM
Edited Jul 1, 2011 at 12:37 AM

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 !

Kevin

Jul 1, 2011 at 8: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 8: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.