1

我在单独的项目中有简单的 ApiController:

<Export("Custom", GetType(ApiController)),
PartCreationPolicy(CreationPolicy.NonShared)>
Public Class CustomController
    Inherits ApiController

    Public Function GetSomething() As HttpResponseMessage
        Dim Result As New Something() With {
             .Code = "Code",
             .SomeField = "Something",
             .SomeField2 = 5
            }
        Return Request.CreateResponse(System.Net.HttpStatusCode.OK, Result)
    End Function

End Class

在谷歌搜索了一段时间后,我设法使用 IHttpControllerSelector 和 IHttpControllerActivator 的自定义实现来解析控制器。但现在得到错误:"No action was found on the controller 'Custom' that matches the name 'GetSomething'"。意味着我必须实现 IHttpActionSelector 并且之后可能还有其他东西......这听起来非常复杂且不合逻辑,因为我没有尝试进行任何自定义处理。任何提示我哪里出错了?

4

1 回答 1

2

在外部库中拥有 WebAPI 控制器似乎非常简单。您需要做的就是注册自定义 AssembliesResolver。Mef 注册已经在加载外部 dll。

诀窍是您不能使用 DefaultAssembliesResolver 并覆盖函数 GetAssemblies()。你必须自己实现 IAssembliesResolver。

这是我的代码,它给出了我所需要的:

Mef 注册(只是加载扩展的一部分):

    Dim ExtensionsCatalog As New DirectoryCatalog(Settings.GetValue("ExtensionsFolder"))
    Dim container As New CompositionContainer(ExtensionsCatalog, defaultCatalogEP)

全球.asax

GlobalConfiguration.Configuration.Services.Replace(GetType(IAssembliesResolver), New Models.CustomAssembliesResolver())

CustomAssembliesResolver 类

    Public Class CustomAssembliesResolver
    Implements IAssembliesResolver

    Public Function GetAssemblies() As ICollection(Of Assembly) Implements IAssembliesResolver.GetAssemblies
        Dim assemblies As List(Of Assembly) = AppDomain.CurrentDomain.GetAssemblies().ToList()
        Return assemblies
    End Function

End Class

现在我有了新的控制器“自动添加自己”并使用 MEF 覆盖/扩展任何基本 WebAPI。

于 2013-05-20T10:08:07.013 回答