OdeToCode IC Logo

WebAPI Tip #1 and #2: HttpStatusCodes and Overriding Conneg

Thursday, March 21, 2013

Henceforth we begin a series of tips and musings on the WebAPI.

Tip #1 – HttpStatusCode is an enum you can use to send specific status codes in a response. Going through the list, it is not always clear what name matches a value you are looking for, so here is a WebAPI controller to dump status codes into JSON.

public class StatusCodesController : ApiController
{
    public HttpResponseMessage Get()
    {
        var type = typeof(HttpStatusCode);
        var values =
            Enum.GetNames(type)                    
                .Select(name => new { name =name, value = (int)Enum.Parse(type, name) });

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new ObjectContent(values.GetType(),
            values,
            Configuration.Formatters.JsonFormatter);

        return response;
    }
}

Tip #2 – The Request.CreateResponse extension method will use a content negotiation strategy to pick the best formatter for the response. In cases where you want to force a specific content type, use the approach in the above code. This example is forcing a JSON request by passing in the JsonFormatter to the ObjectContent ctor (because the XML formatter doesn't like anonymous types).

More to come...