Base controller from another class library doesn't working in web api

后端 未结 2 1691
暗喜
暗喜 2021-01-22 11:43

I have two Web API projects and I have a MarketController and I need to extend the Api controller so I did it.

I created a BaseController class

2条回答
  •  粉色の甜心
    2021-01-22 12:21

    By default MVC looks for all controllers in same assembly of mvc application. The default controller factory creates controller instance based on string 'ControllerName+Controller' like MarketController where market comes from url market/actionname.It will look for MarketController in the same assembly as mvc application.

    To put controller in separate assembly you will have to create your own controller factory or you will have to specify assembly name is app start.

    Once you've created your own custom ControllerFactory, you add the following line to Application_Start in global.asax to tell the framework where to find it:

    ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
    

    Or for simple cases like yours you can do this :

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = "" },
        new[] { "BLLAssembly.Controllers" }
    );
    

    Here BLLAssembly.Controllers is namespace for your BaseController in BLL assembly.

    There is one more advanced way using custom assembly resolver ,i.e IAssembliesResolver The below article tells how to do this with Web Api also,

    http://www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/

提交回复
热议问题