ASP.NET MVC WebAPI 404 error

Viewed 94884

I have an asp.net web forms application running under v4.0 integrated mode.

I tried to add an apicontroller in the App_Code folder.

In the Global.asax, I added the following code

 RouteTable.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = System.Web.Http.RouteParameter.Optional }
 );

When I tried to navigate to the controller at http://localhost/api/Value, I get the 404 error.

The extensionless url is configured in the handler section. I have forms and anonymous authentication enabled for the website.

ExtensionLess url is configured for '*.'

When I hit the url for controller, the request is handled by StaticHandler instead of ExtensionlessUrlHandler-Integrated-4.0.

I have no clue now why the system will throw the error as shown in the image below. Error

20 Answers

Thanks to Shannon, ceinpap, and Shri Guru, the following modification works for me:

  1. WebApiConfig.cs:

    public static void Register(HttpConfiguration config)
    {
        ...
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    
  2. Global.asax.cs:

    protected void Application_Start()
    {
        ...
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        ...
    }
    

The sequence of registering the route, was the issue in my Application_Start(). the sequence which worked for me was

AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);

earlier it was

AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
Related