Sunday, July 19, 2015

GetRouteData() in ASP.NET WebApi

I've been trying to get System.Web.Http.HttpRouteCollection.GetRouteData() to work in ASP.NET WebApi recently, and had a hard time of it. In ASP.NET MVC it's really easy, but there are additional details I couldn't figure out in WebApi. There was even a detailed set of answers on StackOverflow, but when I tried them, they all failed in ways that didn't make sense to me.

And now I have seen it work, so I want to document it. Here's what I did:

  1. In VS 2013, New Project -> Web, ASP.NET Web Application
  2. Select WebAPI. Check "Add unit tests".
  3. Add the following unit test:

And here's a Git repository with the complete working solution.

(Thanks to this blog post for unblocking me.)