Dot-Net
自託管 WebAPI 應用程序引用來自不同程序集的控制器
我遇到了這顆寶石,它似乎接近我想要的。但是,我想使用引用程序集中已經編寫的控制器。
我的第一次破解是引用程序集,設置路由規則和原來的webAPI項目一樣去,但是每次嘗試呼叫自託管服務都會得到400s。我已經通過 Fiddler 挑選了請求的內容,除了地址差異之外,針對 webAPI 項目和自託管項目的請求是相同的。
我覺得這應該相對簡單,但我還沒有找到一個可以接受的答案。
這似乎是一個已知問題。您必須強制 .NET 使用您需要的控制器載入程序集。
在您自行託管 Web API 之前,您應該從參考程序集中檢索您希望由執行時載入的類型。像這樣的東西:
Type controllerType = typeof(ReferencedControllers.ControllerType);這應該從這個程序集中載入控制器,它不會給你 404 錯誤。
Praveen 和 Janushirsha 以前的文章將我引向了正確的方向,我在這裡繼續:
// Not reliable in Release mode : Type controllerType = typeof(ReferencedControllers.ControllerType);因此,您應該替換
IAssembliesResolver為:HttpConfiguration config = new HttpConfiguration(); config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());這是一個實現範例
CustomAssembliesResolverusing 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; } }如果未引用第三方程序集或者您想要後期程序集綁定,則可以輕鬆修改此程式碼。
希望這有幫助。