Search code examples
c#.net-corebackground-service

Get log on user in .net core worker service


I have a .net core 3.1.8 worker service. Is there a way to access the username of the Windows user that is set as the log on user for this service? I don't really see anything related to this in the documentation of the background service. Tried googling, but google only really finds stuff related to HttpContext, which I obviously do not have in a background service.

I only really need this for logging purposes, as in set the creator/modifying user in the DB when something is inserted/updated through the service, so my current solution is putting a serviceUserName property in appsettings.json and read it from there, but that just feels... dirty?


Solution

  • As seen in the comments, you can get user name of current thread with:

    Environment.UserName
    

    Reference:

    https://learn.microsoft.com/en-us/dotnet/api/system.environment.username?view=netcore-3.1