Search code examples
c#castingasp.net-web-api2asp.net-web-api-routing

Cannot cast System.Web.Http.WebHost.Routing.HostedHttpRoute to System.Web.Http.Routing.IHttpRoute


After updating ASP.NET Web API to 2.2 (from nuget package version 4.0 to 5.2) for a Web API solution, I can no longer cast an object of type System.Web.Http.WebHost.Routing.HostedHttpRoute to System.Web.Http.Routing.IHttpRoute.

According to this source of HostedHttpRoute, it implements IHttpRoute so the cast should work. However, this source must be outdated for 5.2...?

Does anyone know if HostedHttpRoute has changed in any way that would cause this issue? If so, please share any information you have about such changes.

If you're wondering why I'm trying to perform this cast - it's part of retrieving all the routes of a web API application and return an HttpRouteCollection. This involves calling the RouteConfig.RegisterRoutes() method in to retrieve a RouteCollection object. Each item in this RouteCollection object is a HttpWebRoute object, which contains a property named HttpRoute of type HostedHttpRoute. Each of these HostedHttpRoute would be cast to an IHttpRoute which is then added to a HttpRouteCollection.


Solution

  • 3The issue was that the application where this casting code is written had API v5.2.3 installed, where the API web application had API v5.2.2 installed, so the IHttpRoute type had a mismatch version problem. For some reason, 5.2.3 works with 4.0, but not 5.2.2. I updated the web app to 5.2.3 and the issue is resolved.