I have 2 controllers in 2 different areas that will display a different page on the home page depending on the type of user.
The controller actions are at;
MyApp.Areas.Buyer.Controllers.SocialController.Index
MyApp.Areas.Client.Controllers.SocialController.Index
These will just show some data on the home depending on the user. When the user logs in I save the type of user in a session and check the user type on every request. I managed to create a middleware that checks the user type and changes the target area.
public async Task InvokeAsync(HttpContext httpContext, UserManager<ApplicationUser> userManager)
{
...
String? k = httpContext.Session.GetString(Contants.ModeSessionKeyName);
var splittedUrl = url.Split('/');
if (url=="/")
{
switch (k)
{
case "_BUYER":
// httpContext.GetRouteData().Values.Add("area", "My");
httpContext.GetRouteData().Values["area"] = "BUYER";
break;
default:
httpContext.GetRouteData().Values["area"] = "Client";
break;
}
}
...
await _next(httpContext);
}
That works fine. Except now there is a conflict between the two routes when I try to run it.
AmbiguousMatchException: The request matched multiple endpoints. Matches:
Is there anyway to prevent this? Can I remove one of the routes at runtime before ASP.NET Core checks and throws the exception?
Here is how the two controllers look like;
[Area("Buyer")]
public class SocialController : Controller
{
[AllowAnonymous]
[HttpGet("/")]
public IActionResult Index()
{
ViewData["Title"] = "My Account";
ViewData["PageHeading"] = "Feeds";
if (!User.Identity.IsAuthenticated)
{
return new RedirectResult("/welcome") { Permanent = false };
}
return View();
}
}
The other controller is exactly the same it just has the attribute [Area("Client")]
The
[HttpGet("/")]forced the method real URL to be "/", you shouldn't use it.You can not have same "real" route. Adding area just make your real URL become
Domain/area/controller/actionformat.So the real URL of your methods should be
domain/buyer/social/indexanddomian/client/social/index.Real URL has to be different. But the input URL "/" can be rewrite the area/controller/action in the middleware. Please clarify the difference of real URL and input URL
You can try the following code for a test.
Areas/Buyer/Controllers/SocialController.cs
Areas/Buyer/Views/Social/index.cshtml
Areas/Client/Controllers/SocialController.cs
Areas/Client/Views/Social/index.cshtml
CustomMiddleware.cs
program.cs
Test1

Then change the middleware
Test 2

Reference :https://geeksarray.com/blog/how-to-use-areas-in-asp-net-core-mvc