我有现有项目ASP.NET MVC 4.我想添加到项目WebApi2。所以我在Nuget中安装了WebApi2并创建了ApiController。当我运行项目然后我收到错误
IControllerFactory' MvcApplication.Infrastructure.NinjectControllerFactory'没有为名称' api'返回控制器。
我的NinjectControllerFactory:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = KernelSingleton.Instance.GetStandardKernel();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
}
修改
WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// TODO: Add any additional configuration code.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Main RouteConfig为空,因为我有两个区域。
internal static class RouteConfig
{
internal static void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
internal static class RouteConfig
{
internal static void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
"User_default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
答案 0 :(得分:1)
因为您已经移动了"默认"要成为某个区域的路线,您需要在Global.asax
。
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
应该是:
WebApiConfig.Register(GlobalConfiguration.Configuration);
AreaRegistration.RegisterAllAreas();
否则,任何以/api
开头的路线都会点击您的默认路线,并寻找名为api
的控制器。