首页 > 解决方案 > 如何避免带有重复控制器名称的 AmbiguousMatchException

问题描述

我有一个跨多个解决方案使用的项目,其中包含一个带有常用视图的控制器。我们还有一个作为该项目的父应用程序的 web,我们正在转换 web 以使用该项目,而不是定义它自己的视图版本,这样当我们更新项目时,我们不必同时更新 web。

我遇到的问题是网络包含一个名为“PlaceholderController”的控制器,并且该项目还包含“PlaceholderController”,所以当运行网络并点击占位符控制器时,我得到一个 AmbiguousMatchException。

我无法重命名这些控制器中的任何一个,更新项目的控制器名称需要触及许多解决方案,而在 Web 中更新控制器名称也需要我们更新大量 URL。

这是解决方案结构的示例

Solution 'PlaceholderEngine'
    -PlaceholderEngine.csproj (Web)
        -Views
            -Home
            -Placeholder
                -ExampleView1.cshtml
             ...
            -More
        -Controllers
            -HomeController.cs
            -PlaceholderController.cs
            ...
            -MoreController.cs
    -PlaceholderModule.csproj (Project included in solution)
        -Views
            -Placeholder
                -ExampleView2.cshtml
        -PlaceholderController.cs (unrelated to PlaceholderController in the PlaceHolderEngine (Web) project)

这是使用相同 PlaceHolderModuler 项目的另一个解决方案的示例

Solution 'OtherWeb'
    -OtherWeb.UI.csproj
    -OtherWeb.Domain.csproj
    -PlaceholderModule.csproj

目前,要使用 Web 项目配置控制器,我们使用在 Startup.cs 中调用的 IMVCBuilder 扩展方法

扩展方法

...
public static IMvcBuilder ConfigurePlaceholderModule(this IMVCBuilder builder){
    var assembly = typeof(PlaceholderController).Assembly;
    return builder.AddApplicationPart(assembly)
        .AddControllersAsServices()
        .AddRazorOptions(o=>
            o.FileProviders.Add(new ManifestEmbeddedFileProvider(assembly)));
}
...

Startup.cs 配置服务

...
    public void ConfigureServices(IServiceCollection services){
        ...
        services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .ConfigurePlaceholderModule();
        ...
    }
...

此设置适用于我们拥有的任何其他项目,但我很难弄清楚如何避免在 PlaceholderEngine web 中配置 PlaceholderModule 引起的 AmbiguousMatchException。有没有办法在 Startup.cs 中路由 PlaceholderModule 的 PlaceholderController 与 PlaceholderEngine 的 PlaceholderController 不同?任何建议表示赞赏。

标签: c#.netasp.net-mvc

解决方案


推荐阅读