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...


Comments
gravatar Fredi Machado Thursday, March 21, 2013
Great tips Scott, thanks!
gravatar MDP Thursday, March 21, 2013
Awesome tips,go ahead ;)
gravatar Stan Drapkin Sunday, March 24, 2013
Enum.GetValues() on HttpStatusCode returns misleading results. We typically expect all enum values to be distinct. This is not the case for HttpStatusCode, however, which maps several names to the same integer value. MultipleChoices = Ambiguous = 300 MovedPermanently = Moved = 301 Found = Redirect = 302 SeeOther = RedirectMethod = 303 TemporaryRedirect = RedirectKeepVerb = 307 The Array returned by GetValues() will have duplicate values, which will get converted to the *1st* match during the cast to HttpStatusCode. Enum.GetNames(typeof(HttpStatusCode)).Select(n => new {name = n, value = (int)Enum.Parse(typeof(HttpStatusCode), n)}).OrderBy(i=>i.value).Dump();
gravatar Scott Allen Sunday, March 24, 2013
@Stan : Good point, updated! Thanks.
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!