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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With