How to get the current logged in user in an Umbraco Content Service Saving event

Posted written by Paul Seal on September 23, 2020 Umbraco

My friend Nik had another question for me today.

He wanted to know how to get the current logged in Umbraco user when you are in the Content Service Saving event.

So I knocked up this example for him and thought it would be a good idea to create a blog post for it so it doesn't get lost in slack messages.

using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Events;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Implement;
using Umbraco.Web;
using Umbraco.Web.Security;

namespace CodeShare.Core.Composing
{
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class SavingEventComposer : ComponentComposer<SavingEventComponent>
    { }

    public class SavingEventComponent : IComponent
    {
        private readonly IUmbracoContextFactory _umbracoContextFactory;

        public SavingEventComponent(IUmbracoContextFactory umbracoContextFactory)
        {
            _umbracoContextFactory = umbracoContextFactory;
        }

        public void Initialize()
        {
            ContentService.Saving += ContentService_Saving;
        }

        private void ContentService_Saving(IContentService sender, ContentSavingEventArgs e)
        {
            IUser currentUser = null;

            // use the umbraco context factory to ensure the umbraco context which we need to get the auth ticket of the user
            using (UmbracoContextReference umbracoContextReference = _umbracoContextFactory.EnsureUmbracoContext())
            {
                var userTicket = umbracoContextReference.UmbracoContext.HttpContext.GetUmbracoAuthTicket();
                if (userTicket != null)
                {
                    currentUser = Current.Services.UserService.GetByUsername(userTicket.Identity.Name);
                }
            }
        }

        public void Terminate()
        {
            // Nothing to terminate
        }
    }
}

Again, I hope someone else finds this useful.