I have found a minor difference in the routing base classes in ASP.NET Web Api which has forced me to write a little helper class which will allow me to define my routes just once. Is there a reason for this? I’m assuming it was too big a change to the framework to make both RouteCollections derive from the same base class or implement the same interface (which would have made this class much simpler)
public static class RouteMapper
{
private class Route
{
public string Name { get; set; }
public string Template { get; set; }
public object Defaults { get; set; }
public Route(string name, string template, object defaults)
{
Name = name;
Template = template;
Defaults = defaults;
}
}
private static List<Route> GetRoutes()
{
return new List<Route>
{
new Route(
"API Default",
"api/{controller}/{id}",
new {id = RouteParameter.Optional})
};
}
public static void AddHttpRoutes(this HttpRouteCollection routeCollection)
{
var routes = GetRoutes();
routes.ForEach(route => routeCollection.MapHttpRoute(route.Name, route.Template, route.Defaults));
}
public static void AddHttpRoutes(this RouteCollection routeCollection)
{
var routes = GetRoutes();
routes.ForEach(route => routeCollection.MapHttpRoute(route.Name, route.Template, route.Defaults));
}
}
What this allows me to do is to call a simple AddHttpRoutes method in both my Global.asax and my integration tests.
Integration Tests
var configuration = new HttpSelfHostConfiguration("http://localhost:20000");
configuration.Routes.AddHttpRoutes();
_server = new HttpSelfHostServer(configuration);
_server.OpenAsync().Wait();
Global.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.AddHttpRoutes();
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Is this a known issue and is it likely to be fixed in a later release of ASP.NET Web Api?
Yes, the routing is slightly different due to the fact that ASP.NET already has routing but we couldn’d depend on it directly since that would prevent Self-host support. We’re still looking at how things could make more sense.