我无法使用ASP.Net Web API 2控制器访问在MVC Project中编写的API。
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);
}
}
答案 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);
}
}