RedirectUrlService Notifications Example
Example of how to use a RedirectUrlService Notification
The RedirectUrlService manages the redirect URLs that Umbraco tracks automatically. A redirect is created when published content changes its URL. For more information, see the URL Redirect Management article.
The service publishes four notifications. The "before" notifications are cancelable, which lets a handler stop a redirect from being created or deleted.
RedirectUrlSavingNotification
Before a redirect is created or updated
Yes
RedirectUrlSavedNotification
After a redirect is created or updated
No
RedirectUrlDeletingNotification
Before a redirect is deleted
Yes
RedirectUrlDeletedNotification
After a redirect is deleted
No
The entities in each notification are IRedirectUrl objects. Each one exposes the Url, Culture, ContentId, and ContentKey of the affected redirect.
Usage
The following example handles the RedirectUrlSavingNotification to stop redirects from being created for a specific part of the site. The redirects being created are available through the SavedEntities property.
using System;
using Umbraco.Cms.Core.Notifications;
namespace MySite;
public class PreventRedirectCreationHandler : INotificationHandler<RedirectUrlSavingNotification>
{
public void Handle(RedirectUrlSavingNotification notification)
{
foreach (var redirect in notification.SavedEntities)
{
if (redirect.Url.StartsWith("/example/", StringComparison.OrdinalIgnoreCase))
{
notification.Cancel = true;
}
}
}
}Canceling a redirect deletion
Because deletions are triggered by an editor, a canceled RedirectUrlDeletingNotification can return a message explaining why. Use CancelOperation to cancel the operation and pass the message at the same time.
Logging deleted redirects
The "after" notifications cannot be canceled. Use them to react once an operation has completed, for example to write a log entry. The following example handles the RedirectUrlDeletedNotification and logs each deleted redirect through the DeletedEntities property.
Registering the handlers
Register the notification handlers in a composer using AddNotificationHandler.
Last updated
Was this helpful?