404 error after adding Web API to an existing MVC Web Application

39,271

Solution 1

It's working!!! I didn't want to believe, but guess what, the problem was related with the Global.asax routing order.

While it doesn't work with:

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

It works with:

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

Crazy, I know.

Solution 2

If you want to use WebAPI inside an existing MVC (5) project you have to do the following steps:
1.Add WebApi packages:

Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.WebHost
Newtonsoft.Json

2.Add WebApiConfig.cs file to App_Start folder:

using System.Web.Http;

namespace WebApiTest
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

3.Add the following line to Glabal.asax:

GlobalConfiguration.Configure(WebApiConfig.Register);

Important note: you have to add above line exactly after AreaRegistration.RegisterAllAreas();

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

Solution 3

"When adding new routes ALWAYS KEEP IN MIND that you have to add specific route on the top followed by more generic route in the end. Otherwise, your web app will never receive proper routing."

The above is the citation from here: http://www.codeproject.com/Tips/771809/Understanding-the-Routing-Framework-in-ASP-NET-MVC

I know the answer is already given, but this could help to understand why we need to put GlobalConfiguration.Configure(WebApiConfig.Register); before RouteConfig.RegisterRoutes(RouteTable.Routes);

Share:
39,271
Luis Gouveia
Author by

Luis Gouveia

Languages: Portuguese (Native), English (C2), French (C2), Spanish (B1) and Russian (A1) Technologies: Azure (SaaS, PaaS and IaaS), Azure Devops, C#, C++, C, ASP.NET Core, Azure Functions, ASP.NET MVC, Web Forms, Java, Entity Framework (Core), NHibernate, IIS, WCF, SOAP, REST, React, HTML5, CSS3, BootStrap, Javascript, jQuery, WEB API, Powershell, xUnit (Unit Tests), T-SQL, PL/SQL, Cosmos DB, Datalake, BlobStorage, Oracle, Azure SQL, SQL Server, SSRS, SSIS, TFS, GIT, SVN, JSON, OAuth, Docker, Kubernetes, Swagger, OData, Cloud Computing, Microservices, Serverless Architecture & CI/CD Pipelines. Methodologies: Scrum/Agile, Waterfall, TDD, DDD, KanBan, Lean, 5S Key Achievements: 2021 - Joins Microsoft! 2021 - Becomes Extia's .NET Architect in Portugal 2019 - Becomes the GFI's Service Center .NET Architect (supporting 20 .NET developers) 2019 - Awarded the GFI's Commitment Ambassador Prize (check photo in linkedin profile) 2019 - Wins the CityWay project for GFI 2018 - Presents the Application Services department (service-center) to the Minister of Economy and GFI's CEO (check photo in profile) 2018 - Wins 2 new projects for GFI: STACKR & ADP - Aéroports de Paris 2018 - ASP.NET MVC Core Master Class at ‘Instituto Politécnico de Setúbal’ (representing GFI) 2018 - Brings a new project from France for GFI's Service Center: STACKR, The insight maker 2017 – Less than 4 years after joining GFI, the turnover of his projects amount to more than 500.000 € 2017 – ASP.NET MVC Core Master Class at ‘Universidade Lusofona’ in Lisbon (representing GFI) 2016 – Project Manager/Tech Lead on “XPO Logistics”, a key client for the GFI’s service center 2016 – Project Manager/Tech Lead on “People Map” 2015 – Project Manager/Tech Lead on “Maxim: Maximus Inventory” 2014 – Team lead on “Pégase 3” 2014 - Hired by GFI as one of the founders of the GFI’s nearshore service center 2013 - Wise Waste TM gets CE certification 2013 - Wise Waste TM becomes the 1st product in Portugal with the following certification: “Common Criteria for Information Technology Security Evaluation” 2013 - 500th Wise Waste System is sold 2011, Valencia (ES) - Wise Waste wins 3rd prize for environ. innovation at EcoFira 2011, Lisbon (PT) - Wise Waste wins 2nd prize for environmental innovation (Environment Ministry) 2010 – Founds the ‘Muteco’ startup after creating an electrical bicycle on its own 2007 - Joins Auto-Sueco 2006 - Internship at CNRS (Centre National de la Recherche Scientifique) in Toulouse, France

Updated on July 08, 2022

Comments

  • Luis Gouveia
    Luis Gouveia almost 2 years

    There's a great question here: How to add Web API to an existing ASP.NET MVC 4 Web Application project?

    Unfortunately, it wasn't enough to solve my problem. I've tried twice to be sure I haven't done anything wrong. I right clicked on "Controllers" and added the item "Web API 2 Controller with actions, using Entity Framework" where I selected my model class and db context. Everything went fine... but still... everytime I've tried to access /api/Rest I was getting a 404 error (The name of my Controller is RestController).