Mr. Bellis Mr. Bellis - 8 days ago 4
C# Question

Web API: A route named 'X' could not be found in the route collection

I have tried all solutions found both here on Stackoverflow and elsewhere on the internet with regards to this error and still we are getting an issue.

So we have .NET API which has a POST method which then returns a CreatedAtRoute response (201). The problem is that when returning the CreatedAtRoute response we get the error "A route named 'X' could not be found in the route collection.", where X is the name of our route.

The Global.asax

protected void Application_Start()

var allDirectRoutes = WebApiConfig.GlobalObservableDirectRouteProvider.DirectRoutes;

WebApi.config - We have the MapHttpAttributes declared before the default route.

public static class WebApiConfig
public static ObservableDirectRouteProvider GlobalObservableDirectRouteProvider = new ObservableDirectRouteProvider();

public static void Register(HttpConfiguration config)
config.Formatters.Add(new JsonMediaTypeFormatter());

// Web API routes


new { id = RouteParameter.Optional }

Controller - GetCompoundById route
This is the route we want to build using the named route

[Route("{id:Guid}", Name = "GetCompoundById")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(CompoundViewModel))]
public async Task<IHttpActionResult> Get(Guid id)
var serviceResult = await Task.FromResult(CompoundService.Get(id));

if (serviceResult == null)
return NotFound();

CompoundViewModel result =
new CompoundViewModel {Id = serviceResult.Id, Name = serviceResult.Name};

return Ok(result);

Controller - Return CreatedAtRoute in the POST action
This is where the error is thrown because the named route is not found.

return CreatedAtRoute("GetCompoundById", new {id = result.Id}, result);

Note: In the WebApi.config I have created an ObservableDirectRouteProvider which allows me to see the routes created on startup and I can see my named route exists in the collection.
enter image description here


The issue was strangely nothing to do directly with the way we were using the named routes or configuring WebAPI routing (which explains why all other posts didn't help me fix it). We found that the issue was a side effect of how we were using StructureMap as our IoC container.

In the StructureMap registry we were calling


which had the strange side-effect of causing the error. By performing a very long and tedious process of elimination I tracked it down to this exact line. Once remove the routing then again worked as expected. I can only presume that this causes some WebApi dependency to load the incorrect type into memory which cannot resolve the routing table.