Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API Route not found

I have just added a new Web API controller to my project. Now, I am trying to invoke the controller from JavaScript. But first I am also interested to manually invoke the route which is not pulling up anything. It says "Page Not Found".

My RegisterRoutes methods is shown below:

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "DefaultApi",
                url: "api/{controller}/{id}",
                defaults: new { id = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

My API controller is called FlightsController:

 public class FlightsController : ApiController
    {
        public IEnumerable<FlightViewModel> GetAllFlights()
        {
            return new List<FlightViewModel>() { new FlightViewModel() { Name = "Some Flight" }};
        }
}

I am trying to access it using the following URL:

http://localhost:54907/api/flights // The resource not found
http://localhost:54907/MyProject/api/flights // resource not found 
api/flights // name not resolved 

What am I doing wrong?

VERSION: I added a new file to my controllers directory which is called "Web API Controller Class (v2.1)

UPDATE: Here is my updated web.config

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            GlobalConfiguration.Configure(WebApiConfig.RegisterRoutes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }
like image 886
john doe Avatar asked Dec 01 '22 14:12

john doe


1 Answers

I was having the similar issues and I decided to download the example from this website and compare the difference. Eventually, I fixed my issue by switching the sequence of the route registering function calls in Global.asax.cs file.

Instead of :

RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.RegisterRoutes);

Call the WebApiConfig.RegisterRoutes first, that is:

GlobalConfiguration.Configure(WebApiConfig.RegisterRoutes);
RouteConfig.RegisterRoutes(RouteTable.Routes);

I'm still investigating the reasons behind. But hope this could help.

like image 99
JoeyZhao Avatar answered Jan 18 '23 13:01

JoeyZhao