Sitecore 404 handling in an Headless .net core application

Within a .net core Sitecore Headless implementation 404 is an important topic and probably any project require some code to handle it, within this post I am explaining how to implement in a simple way…

There are two elements to configure and to pay attention:

  1. Rendering Host customisation

you will need to create a Sitecore controller that’s a catch all controller for all the request to the layout service, here you can find a simple implementation

namespace XXXX.Controllers
{
using Microsoft.AspNetCore.Mvc;
using Sitecore.AspNet.RenderingEngine;
using Sitecore.LayoutService.Client.Exceptions;
public class SitecoreController : Controller
{
public IActionResult Index()
{
var request = HttpContext.GetSitecoreRenderingContext();
if (request == null || request.Response == null)
{
return new EmptyResult();
}
//Check if layout service call return any error
if (request.Response.HasErrors)
{
//loop through errors
foreach (var error in request.Response.Errors)
{
switch (error)
{
//this is the case of 404 errors
case ItemNotFoundSitecoreLayoutServiceClientException _:
Response.Redirect("/404");
break;
}
}
}
return View();
}
}
}

2. Content Delivery / Layout service configuration

Here no customisation is required and if you are happy to have a simple implementation, nothing to do to customise it the rendering host, obviously in most sitecore implementation you may have Redirects / Item Resolvers and custom errors pages on SXA to play a role…

3. Content authoring

Within most of Sitecore implementation you will have an item called 404 defined on the root of the site so that Conent Editors can customise the 404 page to serve to customers…

Limitations

this code sinppets is very simple and may not suit you well within your implementation, as an example not all the customer want to call the Page not found 404 and this approach will support the same name for page not found item for multiple site…. Just to clarify if you have 10 sites, all the 10 sites will be forced to call the PageNotFound page as 404 but obviously each site could have different content to show for 404 page….

Other extension to this code could be to set the status code of 404 page, some SEO expert reccomend do it, others do not consider it mandatory…