我试图弄清楚如何访问ASP.NET控制器之外的当前登录用户名。
例如我正在尝试这样做:
Track Created and Modified fields Automatically with Entity Framework Code First
设置DbContext
。
以下是我的ApplicationDbContext
,但我一直收到错误消息,指出_httpContextAccessor
为null
:
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
答案 0 :(得分:8)
尝试注入IHttpContextAccessor接口
您甚至可以通过创建服务来进一步抽象,以提供您想要的信息(当前登录的用户名)
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";
}
}
您需要在IHttpContextAccessor
中设置Startup.ConfigureServices
以便能够注入它:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IUserResolverService, UserResolverService>();
并根据需要将其传递到您的存储库以记录关联的用户名
答案 1 :(得分:4)
@Nkosi有正确的答案,但请注意IHttpContextAccessor现在位于名称空间下:
Microsoft.AspNetCore.Http;
不再在:
Microsoft.AspNet.Http;