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 }
        );
    }
} 

2 Answers 2

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);
    }
Sign up to request clarification or add additional context in comments.

7 Comments

I can confirm this was a problem for me as well. WebApiConfig.Register needs to go before RouteConfig.RegisterRoutes
Any one knows why ? because if you create a brand new project it will still have the issue
You are a savior!
@ZoranP. can you explain me the reason of that, it works for me but i want to know the reason.
@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.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.