What’s the context of a 404 response in Episerver? Part Two

This is the second and final blog post on the topic of what’s the context of a 404 response in Episerver. Before diving into this blog post make sure you read part one.

We left off knowing what the context was and having set the content reference accordingly in the HTTP property bag. Unfortunately, this is not enough. Since the Episerver ContentRoute will not be valid for the route, it will be passed on to the generic 404 handling, handled either by ASP.NET or the IIS, depending on your configuration. Therefore, we need to intercept the request by adding a second ContentRoute that will take care of rewriting the current request.

In the initialisation module, where we added the first custom content route, we’ll add the second content route that will rewrite the request to the default segments associated with a ContentRoute will be valid for the request. Easy as pie.

As per the code above we add a custom segment to the route. What differs from the first request is that we add this custom segment in the beginning of the route. This allows us to rewrite the context of the request before any of the other default segments try to validate it. Since we know what the “closest” piece of content was in the current request we can rewrite the URL of the context to that piece of content, which then will be resolved by the other segments associated with the route.

Let’s take a look at what happens inside the new custom segment.

This will, of course, make the request valid for an original URL that isn’t. The simple approach to handling this is to add the logic in the view. There could be, admittedly, a much more elegant way of handling this in the template coordinator. But for the sake of this blog post we’ll stick to the controller, where we can decide which view to return for the current request.

One of the strengths of this approach is that the model that is passed to us, for the 404 page, is the content that represents the context of the request. Meaning that for our 404 page we can add logic and provide context for the user, more than the standard “we couldn’t find what you were looking for”-information.

There are refinements to be made, such as adding an Interface for those pages that can display a 404 view, e.g. a ICanDisplay404Page-interface, to decide in the first custom segment if we should rewrite the URL in the second custom segment.

That’s pretty much it. Thanks for reading!

daniel
daniel
Developer
Recommended Posts
Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.

Not readable? Change text. captcha txt

Start typing and press Enter to search