12

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

我的第一次破解是引用程序集,设置路由规则和原来的webAPI项目一样去,但是每次尝试调用自托管服务都得到400s。我已经通过 Fiddler 挑选了请求的内容,除了地址差异之外,针对 webAPI 项目和自托管项目的请求是相同的。

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

4

3 回答 3

10

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

// Not reliable in Release mode :
Type controllerType = typeof(ReferencedControllers.ControllerType);

因此,您应该替换IAssembliesResolver为:

HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());

这是一个实现示例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;
    }
}

如果未引用第三方程序集或者您想要后期程序集绑定,则可以轻松修改此代码。

希望这有帮助。

于 2014-06-26T15:27:41.203 回答
8

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

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

Type controllerType = typeof(ReferencedControllers.ControllerType);

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

于 2012-07-05T07:54:01.723 回答
3

这个链接为同样的问题节省了我的时间:)...

我只需要更改以下语句以适应 selfhost webapi 配置。

GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());

var config = new HttpSelfHostConfiguration("http://localhost:8081");
        config.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());
于 2012-12-15T16:23:51.963 回答