65

I've added Web Api controller to MVC 5 application but all the time I get Error 404 - The resource cannot be found. I've added GlobalConfiguration.Configure(WebApiConfig.Register) to Application_Start()

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

and I have route registred

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
} 
MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
malibeg
  • 2,237
  • 2
  • 17
  • 21

2 Answers2

139

WebApi routing started to work after I've changed the position of Register api method to be above of register routes:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
malibeg
  • 2,237
  • 2
  • 17
  • 21
  • 7
    I can confirm this was a problem for me as well. WebApiConfig.Register needs to go before RouteConfig.RegisterRoutes – Zoran P. May 24 '14 at 11:04
  • 5
    Any one knows why ? because if you create a brand new project it will still have the issue – Kiarash Oct 12 '15 at 00:08
  • 2
    You are a savior! – jekcom Apr 26 '17 at 15:26
  • @ZoranP. can you explain me the reason of that, it works for me but i want to know the reason. – Zeeshan Safdar Oct 29 '19 at 10:22
  • for me GlobalConfiguration.Configure(WebApiConfig.Register); was missing , i've added WebAPI cotroller vs created webAPIconfig.cs file but didn't add to Global.asax – Mohamed Nor Jan 22 '20 at 11:04
  • thank you very much, i have been trying to solve a similar problem all day and this was it. – wayzz Jan 19 '23 at 13:28
  • 1
    @ZoranP. I assume that when calling the application start, the normal routing takes precedent over the api routing therefor the first line of routing when calling the api controller goes through the routeconfig rather than the webapiconfig which will result in a 404 since route is not found. Please if I am wrong someone correct me. – wayzz Jan 19 '23 at 13:31
1

If this may help somebody. In my case the problem was that i deleted default controllers and in RouteConfig.cs file Home controller was still being referenced.