How to configure Web Api 2 to look for Controllers in a separate project? (just like I used to do in Web Api)

前端 未结 8 1776
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 17:40

I used to place my controllers into a separate Class Library project in Mvc Web Api. I used to add the following line in my web api project\'s global.asax to look for contro

相关标签:
8条回答
  • 2020-12-04 18:29

    When using AttributeRouting it is easily forgettable to decorate your methods with the Route Attribute, especially when you are using the RoutePrefix Attribute on your controller class. It seems like your controller assembly wasn't picked up by the web api pipeline then.

    0 讨论(0)
  • 2020-12-04 18:30

    Was running into same scenario and @justmara set me on the right path. Here's how to accomplish the force loading of the dependent assemblies from @justmara's answer:

    1) Override the DefaultAssembliesResolver class

    public class MyNewAssembliesResolver : DefaultAssembliesResolver
    {
        public override ICollection<Assembly> GetAssemblies()
        {
    
            ICollection<Assembly> baseAssemblies = base.GetAssemblies();
            List<Assembly> assemblies = new List<Assembly>(baseAssemblies);
            var controllersAssembly = Assembly.LoadFrom(@"Path_to_Controller_DLL");
            baseAssemblies.Add(controllersAssembly);
            return baseAssemblies;
    
        }
    }
    

    2) In the configuration section, replace the default with the new implementation

    config.Services.Replace(typeof(IAssembliesResolver), new MyNewAssembliesResolver());
    

    I cobbled this syntax together using pointers from this blog:

    http://www.strathweb.com/2013/08/customizing-controller-discovery-in-asp-net-web-api/

    As others have said, you know if you are running into this issue if you force the controller to load by directly referencing it. Another way is to example the results of CurrentDomain.GetAssemblies() and see if your assembly is in the list.

    Also: If you are self-hosting using OWIN components you WILL run into this. When testing keep in mind that the DefaultAssembliesResolver will NOT kick in until the first WebAPI request is submitted (it took me awhile to realize that).

    0 讨论(0)
提交回复
热议问题