Morten Hartvig
Posted on May 28, 2024
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.
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());
}
}
}
}
... and then register it in Program.cs
:
builder.CreateUmbracoBuilder()
.AddBackOffice()
.AddWebsite()
.AddDeliveryApi()
.AddComposers()
.AddNotificationHandler<RoutingRequestNotification, MaintenanceHandler>()
.Build();
Visiting the website before toggling maintenance mode:
Visiting the website after toggling maintenance mode:
π πͺ π
π©
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.