Get log on user in .net core worker service

1.4k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

There are several ways you can get the current user.