Try injecting the IHttpContextAccessor Interface
You can even abstract it further by creating a service to provide just the information you want (Which is the current logged in username)
public interface IUserResolverService {
string GetUser();
}
public class UserResolverService : IUserResolverService {
private readonly IHttpContextAccessor accessor;
public UserResolverService(IHttpContextAccessor accessor) {
this.accessor = accessor;
}
public string GetUser() {
var username = accessor?.HttpContext?.User?.Identity?.Name ;
return username ?? "unknown";
}
}
You need to setup IHttpContextAccessor
now in Startup.ConfigureServices
in order to be able to inject it:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//OR
//services.AddHttpContextAccessor();
services.AddTransient<IUserResolverService, UserResolverService>();
and pass that to your repository as needed to record associated username
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…