How to access RouteTable.Routes.MapHttpRoute?

I have a Web Forms application that I created a few months ago, and I added a web API controller. I tried using the β€œautomatic” routing that I recently saw in the presentation, but all I had was 404. Then I tried to add the routing for the web API controller to my Global.asax using MapHttpRoute, as I saw in several study guides. However, even after adding to the Imports System.Web.Http file, the project does not recognize RouteTable.Routes.MapHttpRoute() I tried to add other namespaces and make sure that I have all the necessary Nuget packages, but I still can’t configure routing for the web -API controller. Does anyone have any recommendations on where to start?

+8
asp.net-web-api webforms asp.net-mvc-routing
source share
4 answers

I found this thread , which indicates that IntelliSense seems to have problems with this, but if you print something like the following, it will build and run:

 RouteTable.Routes.MapHttpRoute("MyApi", "api/{controller}") 
+9
source

If anyone has the same problem in C #, read on.

I also use a web form application and set the route through the Global.asax file. For me, Intellisense was 100% correct, and it would not be built independently. To make this work, I had to add the following directives.

 using System.Web.Http; 

and

 using System.Web.Routing; 

Do not directly use using System.Web.Http.Routing accident. This does not work.

+12
source

You must add a reference to the System.Web.Http.WebHost assembly and make sure that you have

 using System.Web.Http; 

Why? MapHttpRoute is defined in two assemblies in System.Web.Http :

 public static System.Web.Http.Routing.IHttpRoute MapHttpRoute( this System.Web.Http.HttpRouteCollection routes, string name, string routeTemplate) 

Member of System.Web.Http.HttpRouteCollectionExtensions

and in System.Web.Http.WebHost

 public static Route MapHttpRoute( this RouteCollection routes, string name, string routeTemplate, object defaults); 

The first is an extension to HttpRouteCollection

The second is an extension on RouteCollection

So, when you have the webforms application, your Routes are defined in the RouteCollection , so you need a version of WebHost .

This is because the architecture that allows WebApi to be hosted also from IIS. see WebApi Hosting

+11
source

I just created two new web form applications (one using .NET 4, the other 4.5), did nothing but add a web api via nuget, and it worked.

What version of ASP.NET is running in your application? If you are using ASP.NET WebForms 2.0 / 3.5, then it is not supported.

Here is a tutorial that demonstrates how to add a web API to your Web Forms application - http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-aspnet- web-forms

+1
source

All Articles