A Look at ASP.NET 5: Part 5 - The API

The more I work with ASP.NET 5, the more it looks and feels like the old ASP.NET stack except for the hosting. That’s a good thing in most cases, but writing the API that changes.

After dealing with WCF’s bastardized tried to add REST on top of the SOAP stack, I was elated to be introduced to ASP.NET’s Web API some years back. While it let me develop APIs while thinking about REST in more natural forms, it had the problem of being so separated from the MVC stack that many of the facilities had to be duplicated in both stacks. This cognitive dissonance caused many a developer headaches (same class name but in two different namespaces). When I realized that ASP.NET 5 would be merging the two ideas, I was elated…maybe prematurely.

I’ll explain what I’m doing in a series of blog posts and link them all here as I write them. The plan is to write posts about:

Of note here is also the fact that we can have asynchronous actions as easy as using async/await. But if you’ve done ASP.NET Web API, you might think you’re done. Problem is that there is no built-in mapping between verbs and method names (good and bad, depending who you talk to). Instead, you’ll use the attributes to map an action to a verb (e.g. HttpGet, HttpPost, etc.), but include a route pattern to create the mapping.

Now this attribute + route pattern isn’t new and isn’t limited to API controller (it works in view controllers too), it isn’t the only way to handle routing. You can map the routes in Startup.cs if you like, but I find this easier and more comfortable:

Error Handling

A real pet peeve of mine in ASP.NET 5 as it stands (now at Beta 7), is that the helpers that Web API 2 added to more easily return status codes do not exist. Instead, you need to use the HttpStatusCodeResult if you want to return an error condition (and only accepts a numeric version of the status code):

return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);

It get’s marginally worse when you want to return a successful status code (e.g. 201) and return a valid body:

Camel Casing JSON

The last issue is the common case of wanting to camelCase your results. They have simplified this by allowing you to configure this when you add MVC to the Service container (e.g. ConfigureServices in Startup.cs):

So it seems that while they’ve merged the API and View controllers into a single, cohesive set of libraries, there were some tradeoffs. Likely once I use it for a big project, I won’t miss any of the Web API’isms, but who knows. You can opt into using Web API with ASP.NET 5 but I prefer to just toss that out with the new stack instead of using the provided shim to make it work, but it’s nice that it exists since migration is a real need.