简体   繁体   中英

Conflicting Controller actions in Asp Net Core

I am building a UI where there are two different behaviors possible based on some configuration. I want my controllers to be loaded dynamically from different Net core assemblies based on a property value "ProductType" - G or P in appsettings.json

appsetings.json

"ProductType" : "G",

In Startup.cs, on reading the value of property "ProductType" I am loading the corresponding assembly to register the controllers only from that library.

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")))
}

Both "GLibrary" and "PLibrary" has a controller/action named as Security/Login but with different implementations.

SecurityController.cs

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

project.json contains entry for both libraries.

project.json

"GLibrary"
"PLibrary"

Now on hitting the Security\\Login I am getting this error

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)

How can I avoid this AmbiguousActionException?

In Configure method, you can use your route customized for each assembly with defining 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" });
        });
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM