无法在MVC项目中点击Web API 2控制器

时间:2018-07-30 10:42:51

标签: c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我无法使用ASP.Net Web API 2控制器访问在MVC Project中编写的API。

enter image description here

localhost:57323/api/billpayment/getbillers/10有效,但localhost:57323/api/billpayment/getbillers不起作用。

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

1 个答案:

答案 0 :(得分:3)

由于路由的配置方式,您遇到路由冲突。

在标准MVC路由之前,需要将Web API路由添加到路由表中。

更新

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