【问题标题】:Conflicting Controller actions in Asp Net CoreAsp Net Core 中的冲突控制器操作
【发布时间】:2017-03-14 11:33:27
【问题描述】:

我正在构建一个 UI,其中基于某些配置可能有两种不同的行为。 我希望我的控制器根据属性值“ProductType”从不同的网络核心程序集动态加载 - appsettings.json

中的 G 或 P

appsettings.json

"ProductType" : "G",

在 Startup.cs 中,在读取属性“ProductType”的值时,我正在加载相应的程序集以仅从该库中注册控制器。

Startup.cs

string productType = Configuration["ProductType"];
if (productType.Equals("G", StringComparison.OrdinalIgnoreCase))
{
  services.AddMvc()
  .AddApplicationPart(Assembly.Load(new AssemblyName("GLibrary")))
}
else if (productType.Equals("P", StringComparison.OrdinalIgnoreCase))
{
  services.AddMvc()
  .AddApplicationPart(Assembly.Load(new AssemblyName("Plibrary")))
}

“GLibrary”和“PLibrary”都有一个名为 Security/Login 的控制器/操作,但实现不同。

SecurityController.cs

public IActionResult Login()
    {
            //Unique Implementation
            return View();
        }
    }

project.json 包含两个库的条目。

project.json

"GLibrary"
"PLibrary"

现在点击 Security\Login 时出现此错误

An unhandled exception occurred while processing the request.
AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

GLibrary.Controllers.SecurityController.Login (GLibrary)
PLibrary.Controllers.SecurityController.Login (PLibrary)

如何避免这种 AmbiguousActionException?

【问题讨论】:

    标签: c# asp.net asp.net-mvc model-view-controller asp.net-core-1.0


    【解决方案1】:

    Configure 方法中,您可以使用为每个装配定制的路线,并定义namespace

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        string productType = Configuration["ProductType"];
        if (productType.Equals("G", StringComparison.OrdinalIgnoreCase))
        {
          app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional  },
                namespaces: new [] { "GLibrary.Controllers" });
            });
        }
        else if (productType.Equals("P", StringComparison.OrdinalIgnoreCase))
        {
          app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional  },
                namespaces: new [] { "PLibrary.Controllers" });
            });
        } 
    }
    

    【讨论】:

    • 路由命名空间在 .Net Core 中不可用,对吗?这不起作用。
    • 是的。你说的对。它不在核心。我一直在mvc5中使用它。不过,您可以通过覆盖 ActionMethodSelectorAttribute 属性来使用动作约束。你可以这样做:stackoverflow.com/questions/34306891/…
    猜你喜欢
    • 2018-04-18
    • 2020-05-18
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多