简体   繁体   中英

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.

在此输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM