Intercepting Umbraco Events

Umbraco allows you to extend the core functionality by exposing a number of back-office events through its API. It’s actually quite easy to do intercept and extend these events – the hardest part is knowing which event you want to intercept! There is more information about Umbraco Events, including a full list of the events you can intercept here.

In a recent project I worked on, I intercepted a number of Umbraco events to do the following things:

  • add extra information into the Examine search index for blocks of content that would otherwise not have been present in the search index
  • create a custom URL containing the year/month/title when a blog post is published
  • create new content items when a recurring event/meetup is set up

To intercept an event and extend it by adding your own logic, just follow these 3 steps.

Step 1: create a new class that inherits from ApplicationEventHandler:

using Umbraco.Core;

public class MyUmbracoEventInterceptor : ApplicationEventHandler
{
}

Step 2: add a parameterless constructor to your class and add the Umbraco event you want to intercept:

public MyUmbracoEventInterceptor()
{
  ContentService.Saving += Saving;
}

Step 3: create your extension method (in the above example it would be the “Saving” method):

private static void Saving(IContentService sender, SaveEventArgs<IContent> args)
{
  Your extra code goes here…
}

The arguments for your extension method will change depending on the Umbraco event you are extending. Intellisense should hopefully tell you the arguments you need to include. Put altogether it looks something like this:

using Umbraco.Core;

public class MyUmbracoEventInterceptor : ApplicationEventHandler
{
  public MyUmbracoEventInterceptor()
  {
    ContentService.Saving += Saving;
  }

  private static void Saving(IContentService sender, SaveEventArgs<IContent> args)
  {
    Your extra code goes here…
  }
}

So that’s it – pretty simple really! If you have any questions or want me to cover any other Umbraco areas, please add a comment below.

Posted in Code, Umbraco Tagged with: ,

About Maff

Maff Rigby

I'm a certified .Net, Umbraco and AngularJS freelance developer with over 15 years experience in the IT industry. As well as writing code I love to teach; I run a number of workshops and 1-1 coaching sessions on Angular JS and Umbraco, and share what I know and learn here!

I’m social (ish)

Connect with me on LinkedIn, follow me on Twitter, or fail to find me on Facebook.