When using ASP.NET Web API Help Page and the related MVC.ApiExplorer I have valid routes that are accessible via http yet aren't discovered by ApiExplorer. These routes are only found when a general routing rule is used. Usage of a more specific rule (in conjunction with the general one) seems to hide routes from the ApiExplorer.
In an example case of three rules two routes relate to a GET and a POST action on a controller method which take no query parameters go MIA.
public class SomeControllerController : ApiController
{
[HttpPost] public HttpResponseMessage Post(PostObject value) { ... }
[HttpGet] public IEnumerable<DisplayObject> GetAll() { ... }
[HttpGet] public DisplayObject GetById(string id) { ... }
}
When using a routing rule of
routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional
}
);
The routes are discovered appropriately by Api Explorer as
- POST: api/SomeController
- GET: api/SomeController
- GET: api/SomeController/{id}
yet when adding the less generic and more meaningful rule
routes.MapHttpRoute(
name: "ApiSomeControllerDefault",
routeTemplate: "api/somecontroller/{id}",
defaults: new
{
controller = "SomeController",
id = RouteParameter.Optional
}
);
routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional
}
);
Api Explorer only returns
- GET: api/somecontroller/{id}
What is causing some of my routes not to be found?
While this bug is not fixed by ASP.NET Web API team, I'm using my own dumb fix.
My extension method for
IApiExplorer
is doing the same things as originalApiDescriptions
implementation inApiExplorer
class, but instead of removing duplicate actions for different routes, it just returns actions with distinct ID (HTTP method + route). So it returns all declared actions, regardless of the routes count.And, yes, it shamelessly uses reflection to call the private method.
It's easy to use:
HttpConfiguration
parameter added for testability. If you don't care about it, remove the parameter and just useGlobalConfiguration.HttpConfiguration
in the extension method directly.I believe what you are seeing is a known bug with ApiExplorer. What's happening is that the ApiExplorer goes through each route in the route collection and checks if the controller and its actions can be resolved.
In this case, for example, the action "GetById" can be explored by both the above routes, which ApiExplorer incorrectly assumes to be causing a conflict due to ambiguous matching and it tries to filter out duplicate actions, which in this case is causing all the actions to be filtered/removed. Since this bug is in ApiExplorer(which is part of main WebAPI core), i am afraid we cannot fix it anytime soon.