将 WebApi 2 添加到现有项目 - Ninject

Add WebApi 2 to existing project - Ninject

我有现有项目 ASP.NET MVC 4。我想添加到项目 WebApi2。所以我在 Nuget 中安装 WebApi2 并创建 ApiController。当我 运行 项目然后我得到一个错误

The IControllerFactory 'MvcApplication.Infrastructure.NinjectControllerFactory' did not return a controller for the name '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 }
        );
    }
}

由于您已将 "default" 路线移动为一个区域,因此您需要颠倒 Global.asax 中的注册顺序。

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);

应该是:

WebApiConfig.Register(GlobalConfiguration.Configuration);

AreaRegistration.RegisterAllAreas();

否则,任何以 /api 开头的路由都会到达您的默认路由并查找名为 api.

的控制器