I have a controller which serves up 'static pages' with a key column which allows for a URL to be entered. For example, http://hostname/about should route to a controller called StaticPages and any other URL which does not link to a controller (with or without action).
The intention is for the routing to work in the following order:
- Area routes
- Controller routes (with/without action)
- Default route - static page lookup through
StaticPagescontroller
I have the following routing configured, however I am unable to achieve the above configuration.
If I navigate to a static page (i.e. /about) this works, however if I navigate to a controller without an action specified (i.e. /blog), I get a 404 which suggests its skipping to the bottom route pattern. If I use a controller and action (i.e. /blog/index) this works correctly, so it appears to be expecting an action, which I'd rather be set as index by default.
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
"admin-area",
"admin",
"admin/{controller}/{action}/{Id?}");
endpoints.MapControllerRoute(
name: "admin-users",
pattern: "admin/users/{action=Index}/{Id?}",
defaults: new { controller = "UserAdmin", action = "Index" });
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "StaticPage-Default",
pattern: "{key}",
defaults: new { controller = "StaticPages", action = "Details" });
endpoints.MapRazorPages();
});
How can I acheive the described configuration?
/aboutand/blogboth matchdefaultandStaticPage-Defaultroutes, with the latter being a better fit. I don't see a way around this with routing alone - perhaps some additional work/redirects in theStaticPagecontroller, which effectively becomes your catch-all. Alternatively, if there are just a few controllers such as/blog, you can list them explicitly:pattern: "/blog/{action=Index}/{id?}", or use[Route]attribute on each controller. I don't see a better solution...