Prerelease Feature — Automatically-generated help

Search NuGet for the WebAPI test client (Search `testclient` and make sure you allow prerelease software) and you’ll add a really rather sexy feature to your site. It’s an automatic help generator for your site, so that if you go to `http://myapp/help` you get an HTML site allowing you to see all your URLs, their formats, what methods and parameters they take. It also allows you to execute the methods, giving you an in-browser form for building requests. In a recent project, I built something similar — I recognised the need — but this is just miles ahead of mine.

This is something I’ve only seen in a demo, but it looks like a very sweet addition to your site, at least in debug mode. It means you should be able to write a method then see it work in the browser without having to build a ‘proper’ client for it. Unlike the familiar testing pattern where you new up a controller and execute its methods, this tests the whole architecture of your site, including all the serious bits you need to test about model binding, error handling, etc.

Content Negotiation And Response Types

Type an address into the browser and the HTTP request from the browser contains a header like this;


HTTP GET /foo/bar
Accept: text/html,application/xhtml+xml,...

and this `Accept` header is a signal to the application of the kind of content that it’s expecting back. If the browser responds with a web page, it might have a response header like so;

Content-Type: text/html
<!DOCTYPE HTML>
<html lang="en">
<...

So there’s a conversation going on here; the client says ‘I’d like the HTML at /foo/bar’ and the server says ‘Here’s a document!’ That’s the basic pattern repeated over and over during normal web browsing. But this system is fairly flexible. What if /foo/bar represents a resource and you don’t want HTML, but want JSON instead? You can request this;


HTTP GET /foo/bar
Accept: application/json

And if the server can respond with JSON, it will. This is the sort of thing jQuery does when you write


$.getJSON(...);

This is really interesting, because it means that the same URL, with the same verb, can return two totally different representations. This process, this interaction between the `Accept` and `Content-Type` headers, is known as *content negotiation*.

So this little mechanism has some interesting applications. Imagine you are doing a project management app, and you decide to use a URL like this;


/api/Projects/1

This URL represents the resource of ‘Project #1’. But it doesn’t imply anything about the form of the response. If we request


GET /api/Projects/1 HTTP/1.0
Accept: application/json

Then we might expect the response body to contain


{
"ProjectId": 1,
"Name", "Adveriting Campaign"
}

But if we make this request;


GET /api/Projects/1 HTTP/1.0
Accept: application/xml

Then we might expect to recieve this body;


<Project>
<ProjectId>1</ProjectId>
<Name>Advertising Campaign</Name>
</Project>

Now, this is what you see in the OData specification — the same resource, at the same URI, with two different representations. And you’re not just limited to two. Why not return an HTML description if the request asks for `text/html`, or YAML if that’s what the client asks for?

WebAPI lets you add new representations to your system. In your Global.asax, you’ll have an `HttpConfiguration` instance floating around — it’s the object you add routes to. But it also has a member called `Formatters` which is a list of message formatters. The default list includes formatters for JSON, XML, and Form Url Encoding. The first two are for Web/HTTP/REST-style apps; the third is to interpret HTML Form posts. These objects do bi-directional translation; so that if your controller method looks like this;


public Project Get(int id)
{
... do work here...
}

It’s the formatter which determines how the `Project` instance returned by your method is converted into the JSON or XML returned in your HTTP response. Add a new formatter, and your system is now capable of returning a new representation without you having to change your controller method at all. Sweet!

And this also works the other way. The same formatter will take an HTTP request and turn it back into object instances, so that something like this;


public void Put(Project project)
{
... update your project here ...
}

Has the same process — the `Project` instance passed as a parameter has been constructed by the object in config.Formatters. This process is known as Model binding. if you want to look into it further. An example — binding using the Google protobuf format — exists on gitHub in the WebAPIContrib project — https://WebAPIContrib/WebAPIContrib.

First-class HTTP programming is available in WebAPI

Typically, a WebAPI method might look like this;


public Project Get(int id)
{
return this.repo.GetProject(id);
}

And what we’re seeing here is a method that returns a Project object — or rather, a Project object that is later converted into a JSON object…

So it may be that you need to do a whole lot more — say, in sniffing HTTP headers for a particular purpose, or returning more interesting things in the response. So here’s how you would alter the above method;


public HttpResponseMessage Get(HttpRequestMessage request)
{
if (request.Headers[...])
...
}

And now you’re able to do anything you like with the request — you’ve got full control if you need it. It’s the ‘escape hatch’ out of the sometimes-too-helpful set of conventions. Not something for everyday, but something to use when all else fails, I think.

Lightweight Architeture for everyone with ASP.NET Web API — Christian Weyer

This was by far the most pragmatically useful of the sessions so far. We’ve just started using WebAPI and it’s clear that there’s loads more to it than we’re using. Of vital importance to me was an understanding of just how the magic works.

It seems to me that when you get into a new technology, it’s always pretty fraught. Or it should be, because you should be always asking yourself, ‘Am I doing this the right way? Is this the way that a pro would do it, or is it the way an amateur hacker would do it?’ Christian Weyer helped point me down the right path. Luckily, much of the things we’ve been doing are right, and the rest are easy to address.

First up, then — what is WebAPI and why do we care?

Well, WebAPI is a way to build HTTP APIs for your services. The HTTP API is designed to live between the client app — be it web page, console app, Windows Forms app, or iOS app — and provide all the business logic and database logic.

There are a raft of tips, so rather than smashing them all into one big blog post, I’m going to post things one at a time. I’ll tag them all `WebAPI` and `DevWeek` so you can search them out more easily.