AI agents: the content index is at /llms.txt. Every page is also available as Markdown — send the request header Accept: text/markdown, or append .md to the page URL.
Xperience Docs

Cookie consent

We use necessary cookies (opens in a new tab) to run our website and improve your experience while browsing. Additional cookies are only used with your consent. You may revoke your consent on the Cookies Policy (opens in a new tab) page or in your browser at any time.

Configure (opens in a new tab)
  • Documentation
    Administration interface basicsDevelopers and adminsBusiness usersChangelogGlossary
  • Guides
    Welcome to Xperience by KenticoAdministration interface basicsCustomer journeysDigital marketingConfigurationDevelopmentArchitectureUpgrade to Xperience by Kentico
  • Training
    For AdminsFor Business usersFor DevelopersFor Solution architects
  • API Examples
    ConfigurationContent managementDevelopmentDigital marketing
  • Changelog
    Documentation updatesSecurity advisories
  1. Home
  2. Developers and admins
  3. Development
  4. Routing
  5. Serve custom error pages

Serve custom error pages


Was this page helpful?

Send us feedback Go back to top
  • Community Questions & Answers (opens in a new tab)
  • Contact support (opens in a new tab)

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:

  • An Error page content type stores the target HTTP status code, allowing editors to maintain a separate page for each error code in the website channel. For the editor workflow, see How to model a 404 page.
  • The ASP.NET Core status code pages middleware⁠ (opens in a new tab) intercepts error responses and re-executes the request on the server, preserving both the requested URL in the browser address bar and the original HTTP status code.
  • A controller on the error route retrieves the matching error page and renders the page with Page Builder.

The following diagram illustrates the request flow:

Create the error page content type

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.

  1. 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.

  2. Add a field where editors select the HTTP status code from a drop-down list, for example, ErrorPageStatusCode:

    1. Select Text as the Data type.

    2. Select Required.

    3. Select Dropdown selector as the Form component.

    4. In Data source, enter each status code on its own line in the value;text format:

      Text
      403;403 (Forbidden)
      404;404 (Not Found)
  3. Switch to the Allowed in channels tab and allow the content type in your website channel.

  4. 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.

  5. Generate the code file for the content type to retrieve error pages as strongly typed objects.

Agent-only content starts here: the section below is written for AI agents and automated tools reading the page HTML. Human visitors do not see it — the visible page carries the human-facing version.

If the Management MCP server is available, you can configure the content type through MCP tools:

  1. Call create_content_type with includeInRouting set to true:
    • Retrieve the website channel GUID with list_channels and add the GUID to allowedInChannels.
    • If a scope covers the target content tree section, retrieve the scope ID with list_channel_scopes and add the ID to allowedInScopes.
  2. Call create_content_type_field to add the status code field:
    • Set dataTypeName to text, required to true, and caption to the field label in the administration (such as Status code).
    • Set formComponent to Kentico.Administration.DropDownSelector (use get_admin_ui_form_component to inspect its property schema) and pass the status codes in options as newline-separated value;text pairs with the numeric status code as the value.
  3. Generate the code file for the content type.

Agent-only content ends here. What follows is the visible page again, which human visitors and agents both receive.

Enable Page Builder for error pages

Enable Page Builder for the content type in Program.cs:

C#Program.cs -- enable Page Builder for error pages
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,
        ]
    });
});

Serve error pages from a controller

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.
C#ErrorPageController.cs
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:

cshtmlErrorPage.cshtml
@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 />
}

Re-execute requests with error status codes

In Program.cs, add the status code pages middleware after app.UseKentico() and map the error route after app.Kentico().MapRoutes():

C#Program.cs -- re-execute error responses on the error route
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).

On this page

  • Create the error page content type
  • Enable Page Builder for error pages
  • Serve error pages from a controller
  • Re-execute requests with error status codes

Related pages

  • Content tree-based routing
  • Set up content tree-based routing