I have 2 routes mapping that can handle the same route, however one is dynamic from CMS and other uses different controller, something like
app.MapControllerRoute(
name: "Dynamic",
pattern: "/{urlPath:regex(urlA|urlB)}/{slug}",
defaults: new { controller = "Controller1", action = "Index" });
app.MapControllerRoute(
name: "NonDynamic",
pattern: "/{slug}/{*path}",
defaults: new { controller = "Controller2", action = "Index" });
How can I try Controller2 or NonDynamic
if Dynamic
-> Controller1 returns 404.
Problem is that I don’t know if Controller1 can handle it until I try to handle it and check if CMS has that page, but if not, I want to handle it with completely different controller2
RedirectTo
is not an option – I don’t want to have 301 or 302 redirects.
It does also seems to be not possible to use Action from different controller in another controller and keep context.
I could copy all the logic from Controller2 to Controller1, and just use different action based on cms response, but this is a mess and I don’t want to mix those 2 controllers.
Is there a way to return from controller and tell the app to keep looking for another route match ?
2
Answers
Here’s a middleware that you can notify on the way down the pipeline by setting a magic
HttpContext.Item
. When it detects this, it finds the endpoint you want to execute and sends it back up the middleware pipeline. This is going to break in all kinds of ways, but it seems to work for the specific case in your question.In Controller1:
Instead of trying to fiddle with custom routing etc. why not have a single controller that handles both cases using an (injected) Chain of Responsibility?
At the controller level, you might have something like this (I haven’t checked if this compiles, so there may be typos):
You’ll then have (at least) two implementation of the
IMyService
interface. The first one queries your CMS system:The second implementation of
IMyService
contains your fallback behaviour:Finally, you wire up the (small)
IMyService
Chain of Responsibility like this:It may be more complex, but it’s less complicated because you won’t be mucking around with exotic framework features, but rather taking advantage of well-understood design patterns.