自托管WebAPI应用程序引用来自不同程序集的控制器

Ros*_*oss 10 .net self-hosting asp.net-web-api

我遇到了这个宝石,它似乎与我想要的很接近.但是,我想使用已引用的程序集中已编写的控制器.

我的第一个破解是引用程序集,设置路由规则与原始webAPI项目相同并且去,但每次尝试调用自托管服务时我都会得到400.我已经用Fiddler选择了请求的内部,除了地址差异之外,对webAPI项目和自托管项目的请求是相同的.

我觉得这应该是相对简单的,但我没有找到一个可以接受的答案.

Eri*_*dil 9

以前Praveen和Janushirsha的帖子引导我进入正确的方向,我在这里继续:

// Not reliable in Release mode :
Type controllerType = typeof(ReferencedControllers.ControllerType);
Run Code Online (Sandbox Code Playgroud)

所以,你应该替换IAssembliesResolver为:

HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());
Run Code Online (Sandbox Code Playgroud)

这是一个实现的例子 CustomAssembliesResolver

using System.Web.Http.Dispatcher;
internal class CustomAssembliesResolver : DefaultAssembliesResolver
{
    public override ICollection<System.Reflection.Assembly> GetAssemblies()
    {
        var assemblies = base.GetAssemblies();

        // Interestingly, if we push the same assembly twice in the collection,
        // an InvalidOperationException suggests that there is different 
        // controllers of the same name (I think it's a bug of WebApi 2.1).
        var customControllersAssembly = typeof(AnotherReferencedAssembly.MyValuesController).Assembly;
        if (!assemblies.Contains(customControllersAssembly))
            assemblies.Add(customControllersAssembly);

        return assemblies;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果未引用第三方程序集或者您希望延迟装配绑定,则可以轻松调整此代码.

希望这有帮助.


小智 6

这似乎是一个已知问题.您必须强制.NET使用您需要的控制器加载程序集.

在您自己托管Web API之前,您应该从参考程序集中检索要由运行时加载的类型.像这样的东西:

Type controllerType = typeof(ReferencedControllers.ControllerType);
Run Code Online (Sandbox Code Playgroud)

这应该从这个程序集加载控制器,它不会给你404错误.