Changing the PublishedContent for the current request in Umbraco

hartviglarsen

Morten Hartvig

Posted on May 28, 2024

Changing the PublishedContent for the current request in Umbraco

Using Umbraco's notifications handlers it is possible to override the PublishedContent being loaded for the current request.

The example below assumes you have a maintenance mode you can toggle in you Backoffice. When enabled, every page request to your website should display the maintenance page.

Image description

Start by creating a MaintenanceHandler.cs file:

using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.Notifications;

namespace Adventures
{
    public class MaintenanceHandler : INotificationHandler<RoutingRequestNotification>
    {
        public void Handle(RoutingRequestNotification notification)
        {
            var request = notification.RequestBuilder;

            var website = request.PublishedContent?.Root();
            if (website == null) return;

            var isInMaintenanceMode = website.Value<bool>("maintenanceMode");
            if (!isInMaintenanceMode) return;

            var maintinancePage = website.Value<IPublishedContent>("maintenancePage");
            if (maintinancePage != null)
            { 
                // If maintinance is enabled and the page exists 
                // we set the content for the request and change the template
                request.SetPublishedContent(maintinancePage);
                request.TrySetTemplate(maintinancePage.GetTemplateAlias());
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

... and then register it in Program.cs:

builder.CreateUmbracoBuilder()
    .AddBackOffice()
    .AddWebsite()
    .AddDeliveryApi()
    .AddComposers()
    .AddNotificationHandler<RoutingRequestNotification, MaintenanceHandler>()
    .Build();
Enter fullscreen mode Exit fullscreen mode

Visiting the website before toggling maintenance mode:

Image description

Visiting the website after toggling maintenance mode:

Image description

πŸ’– πŸ’ͺ πŸ™… 🚩
hartviglarsen
Morten Hartvig

Posted on May 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related