I am attempting to create a very flexible routing system that allows users to configure their own publishable url paths to their own content pages, sort of like a CMS. To achieve this, I created a generic controller and route that accepts 3 parameters in this form:
https://localhost:8080/{route1}/{route2}/{route3}
This is my controller:
public class XController : Controller
{
[HttpGet("{route1?}/{route2?}/{route3?}")]
public async Task<IActionResult> Index([FromRoute] string? route1, [FromRoute] string? route2, [FromRoute] string? route3)
{
if (User == null || User.Identity == null || !User.Identity.IsAuthenticated)
return Unauthorized();
//do some stuff here
return View("/views/X/Index.cshtml", model);
}
}
And this works great. However, I still want to use some "predefined" routes for special functions, such as logging in, account management, payments, etc. So my thinking is to have some predefined routes for these special controllers, and then everything else goes to the generic controller defined above. Unfortunately, EVERYTHING, even my "predefined" routes are going to the generic controller. I have routing defined like this:
app.MapControllerRoute(
name: "default",
defaults: new { controller = "Home", action = "Index" },
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "account",
defaults: new { controller = "Account", action = "Index" },
pattern: "{controller=Account}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "x",
defaults: new { controller = "X", action = "Index" },
pattern: "{route1?}/{route2?}/{route3?}");
So, for example, if I navigate to https://localhost:8080/account/login, the generic controller defined above is still handling the request, instead of my "Account" controller. I would like requests to my "predefined" routes to be handled by their respective named controllers, and everything else to be handled by the generic controller.
Am I trying to achieve something that is not doable, or is there a better way of doing this? Or, am I perhaps missing something simple? How can I have a handful of predefined routes to named controllers, and then every other route that does not match those controllers be handled by the generic (controller-less) controller?
pattern: "Account/{action=Index}/{id?}"{route1}/{route2}/{route3}in yourXController. But what you should look for the map wildcard (that I shared in the previous comment) or a fallback routeapp.MapFallback()to redirect to theXControllerIndexaction. Then, within the action, you can extract the route parameter. But the downside is it could be shown "/X/Index/{original route}" URL in the browser.