DEV Community

Morten Hartvig
Morten Hartvig

Posted on

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

Top comments (0)