By default, when a request ends with an error status code (such as HTTP 404 Not Found when no route matches the URL), ASP.NET Core returns only the status code and an empty response body. To display custom error pages that editors manage in the content tree and design with Page Builder, you can route error responses to a custom controller:
The following diagram illustrates the request flow:
This content type gives each error response a routable content-tree item that editors can open in preview and Page Builder, where editors can customize the page experience as required.
Create a content type for Pages, for example, Error page with the code name Acme.ErrorPage. Keep Include in routing selected to allow editors to open their custom error pages in preview and Page Builder.
Add a field where editors select the HTTP status code from a drop-down list, for example, ErrorPageStatusCode:
Select Text as the Data type.
Select Required.
Select Dropdown selector as the Form component.
In Data source, enter each status code on its own line in the value;text format:
403;403 (Forbidden)
404;404 (Not Found)Switch to the Allowed in channels tab and allow the content type in your website channel.
If a scope covers the part of the content tree where editors manage error pages, switch to the Allowed in scopes tab and allow the content type in that scope.
Generate the code file for the content type to retrieve error pages as strongly typed objects.
Enable Page Builder for the content type in Program.cs:
using Acme;
using Kentico.Content.Web.Mvc.Routing;
using Kentico.PageBuilder.Web.Mvc;
using Kentico.Web.Mvc;
// ...
builder.Services.AddKentico(features =>
{
// ...
features.UseWebPageRouting();
features.UsePageBuilder(new PageBuilderOptions
{
ContentTypeNames =
[
// ...
ErrorPage.CONTENT_TYPE_NAME,
]
});
});Create a controller with two actions to handle direct page requests and re-executed error requests:
Index serves Error page items under their own URLs (mapped via RegisterWebPageRoute), allowing editors to open the pages in preview and Page Builder. On the live site, the action sets the response status code from the page field to prevent search engines from indexing the error page as a regular page.Error handles re-executed error requests by retrieving the Error page for the given status code and rendering the page with that status code. Because content tree-based routing populates the page data context only on standard page routes, the action initializes the data context manually with IWebPageDataContextInitializer to support Page Builder widgets. If no website channel matches the request domain (such as when a request targets the server's IP address directly) or no error page matches the status code, the action returns only the status code.using System.Linq;
using System.Threading.Tasks;
using CMS.ContentEngine;
using CMS.DataEngine;
using CMS.Websites;
using CMS.Websites.Routing;
using Codesamples;
using Codesamples.Routing.ErrorPages.Controllers;
using Kentico.Content.Web.Mvc;
using Kentico.Content.Web.Mvc.Routing;
using Microsoft.AspNetCore.Mvc;
[assembly: RegisterWebPageRoute(
contentTypeName: ErrorPage.CONTENT_TYPE_NAME,
controllerType: typeof(ErrorPageController),
ActionName = nameof(ErrorPageController.Index))]
namespace Codesamples.Routing.ErrorPages.Controllers;
public class ErrorPageController(
IContentRetriever contentRetriever,
IWebPageDataContextInitializer dataContextInitializer,
IWebsiteChannelContext websiteChannelContext,
IInfoProvider<ContentLanguageInfo> languageProvider)
: Controller
{
private const string VIEW_PATH =
"~/Routing/ErrorPages/Views/ErrorPage.cshtml";
// Serves an error page under its own URL, for example, in preview
// and in Page Builder.
public async Task<IActionResult> Index()
{
var page = await contentRetriever.RetrieveCurrentPage<ErrorPage>();
// On the live site, keeps search engines from indexing the error
// page as a regular page.
if (!websiteChannelContext.IsPreview)
{
Response.StatusCode = int.Parse(page.ErrorPageStatusCode);
}
return View(VIEW_PATH, page);
}
// Serves the error page for the status code of a re-executed request
public async Task<IActionResult> Error(int code)
{
// Returns the bare status code when no website channel matches the
// request domain.
if (websiteChannelContext.WebsiteChannelID == 0)
{
return StatusCode(code);
}
var statusCodeField = nameof(ErrorPage.ErrorPageStatusCode);
// Retrieves the error page from the current website channel in the
// preferred language of the request, or in a fallback language when
// the page has no variant in that language.
var pages = await contentRetriever.RetrievePages<ErrorPage>(
new RetrievePagesParameters(),
query => query
.Where(where => where
.WhereEquals(statusCodeField, code.ToString()))
.OrderBy(nameof(WebPageFields.WebPageItemID))
.TopN(1),
new RetrievalCacheSettings(
cacheItemNameSuffix: $"{statusCodeField}|{code}"));
var page = pages.FirstOrDefault();
if (page is null)
{
return StatusCode(code);
}
var pageLanguage = await languageProvider.GetAsync(
page.SystemFields.ContentItemCommonDataContentLanguageID);
// Initializes the page data context for Page Builder, which content
// tree-based routing sets only on standard page routes.
dataContextInitializer.Initialize(new RoutedWebPage
{
WebPageItemID = page.SystemFields.WebPageItemID,
WebPageItemGUID = page.SystemFields.WebPageItemGUID,
LanguageID = pageLanguage.ContentLanguageID,
LanguageName = pageLanguage.ContentLanguageName,
ContentTypeID = page.SystemFields.ContentItemContentTypeID,
ContentTypeName = ErrorPage.CONTENT_TYPE_NAME,
WebsiteChannelID = websiteChannelContext.WebsiteChannelID,
WebsiteChannelName = websiteChannelContext.WebsiteChannelName
});
Response.StatusCode = code;
return View(VIEW_PATH, page);
}
}Both actions render the same view, which contains the editable area where editors place widgets:
@using Codesamples
@addTagHelper *, Kentico.Content.Web.Mvc
@model ErrorPage
@{
Layout = "_BaseLayout";
ViewData["Title"] = $"Error {Model.ErrorPageStatusCode}";
}
@section Head {
<page-builder-styles />
}
<main class="mx-auto w-full max-w-7xl px-4 py-8">
<editable-area area-identifier="main" />
</main>
@section Scripts {
<page-builder-scripts />
}In Program.cs, add the status code pages middleware after app.UseKentico() and map the error route after app.Kentico().MapRoutes():
using Kentico.Web.Mvc;
using Microsoft.AspNetCore.Builder;
// ...
app.UseKentico();
// ...
app.UseStatusCodePagesWithReExecute("/error/{0}");
app.Kentico().MapRoutes();
app.MapControllerRoute(
name: "error",
pattern: "error/{code:int}",
defaults: new { controller = "ErrorPage", action = "Error" });Make sure no higher-priority endpoint (such as a catch-all route registered before the error route) matches /error/{code}, or re-executed requests will not reach the Error action. For details on route precedence and error handling, see URL matching (opens in a new tab) and Handle errors in ASP.NET Core (opens in a new tab).