使用 WCF 的 MVC5 和 WebAPI 自定义路由

MVC5 and WebAPI custom Routing with WCF

我有一个 MVC5 应用程序用作框架并使用插件来扩展功能。每个插件都是它自己的 MVC5/WebAPI 项目,我将我的框架项目配置为动态安装插件和检索嵌入式资源。

我的问题是每个插件都可以有 WCF Web 服务、WebAPI 端点和标准 MVC 控制器。例如,我的目录结构可能是:

MyFramework
    Resources
    Controllers (my framework level controllers)
    Plugins
        CoolNewPlugin
             Services
                 CoolService.svc
             Controllers
                CoolAPIController
        OtherPlugin
             Controllers
                OtherAPIController
        CollectionOfPlugins
             AnotherPlugin
                Services
                    AnotherWCFService.svc
        etc....

我的目标是提供以下路线:

/api/REST/{插件}/{控制器}/{操作}

/api/SOAP/{插件}/Services/Servicename.svc

本质上,我想对尝试使用 Web 服务(SOAP 或 REST)的最终用户隐藏应用程序目录结构的复杂性。

我认为我已经使用自定义 IHttpControllerSelector 处理了 REST 内容。

问题出在 WCF 服务端点上。它们在每个插件内部独立定义(每个插件都有自己的 web.config 文件供其服务使用),因此我不能只修改元素以支持其他地址。

在上面的示例中,SOAP 服务端点当前看起来像:

http://example.com/plugins/CoolNewPlugin/Services/CoolService.svc

http://example.com/plugins/CollectionOfPlugins/AnotherPlugin/Services/AnotherWCFService.svc

而我想要的是:

http://example.com/api/SOAP/CoolNewPlugin/Services/CoolService.svc

http://example.com/api/SOAP/AnotherPlugin/Services/AnotherWCFService.svc

感谢您的帮助。

您需要做的是动态创建 WCF 端点,而不是使用 web.config 上的配置。通过这种方式,您可以在所需 URL 中托管 WCF 地址。您可以在此处使用 MSDN 文档执行此操作:How to: Create a Service Endpoint in Code

您可能还必须忽略 MVC/Web 的路由配置代码中的路由 API。