Search code examples
c#asp.net-web-apiasp.net-web-api2asp.net-web-api-routing

Unable to hit Web API 2 controller in MVC Project


I am unable to hit API that I have written in MVC Project using ASP.Net Web API 2 controller.

enter image description here

localhost:57323/api/billpayment/getbillers/10 works but localhost:57323/api/billpayment/getbillers doesn't work.

WebAPI.config

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

Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

Solution

  • You are experiencing route conflicts because of how the routes are configured.

    Web API routes need to be added to the route table before standard MVC routes.

    Update

    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register); //<-- This MUST come before
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes); //<-- THIS to avoid conflicts
            BundleConfig.RegisterBundles(BundleTable.Bundles);        
        }
    }