C# Asp Net核心中的冲突控制器操作
我正在构建一个UI,其中基于某些配置可能有两种不同的行为。 我希望根据appsettings.json中的属性值“ProductType”-G或P,从不同的Net core程序集中动态加载控制器C# Asp Net核心中的冲突控制器操作,c#,asp.net,asp.net-mvc,model-view-controller,asp.net-core-1.0,C#,Asp.net,Asp.net Mvc,Model View Controller,Asp.net Core 1.0,我正在构建一个UI,其中基于某些配置可能有两种不同的行为。 我希望根据appsettings.json中的属性值“ProductType”-G或P,从不同的Net core程序集中动态加载控制器 "ProductType" : "G", "GLibrary" "PLibrary" appsetings.json "ProductType" : "G", "GLibrary" "PLibrary" 在Startup.cs中,在读取属性“ProductType”的值时,我正在加载相应的程序集
"ProductType" : "G",
"GLibrary"
"PLibrary"
appsetings.json
"ProductType" : "G",
"GLibrary"
"PLibrary"
在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")))
}
public IActionResult Login()
{
//Unique Implementation
return View();
}
}
“GLibrary”和“PLibrary”都有一个名为Security/Login的控制器/操作,但实现方式不同
SecurityController.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")))
}
public IActionResult Login()
{
//Unique Implementation
return View();
}
}
json包含两个库的条目
project.json
"ProductType" : "G",
"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)
如何避免这种含糊不清的操作异常?在
配置
方法中,您可以通过定义命名空间
为每个程序集自定义路由
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属性来使用动作约束。您可以这样做: