[英]Injecting IHttpContextAccessor into ApplicationDbContext ASP.NET Core 1.0
I am trying to figure out how to get access to the current logged in username outside of an ASP.NET Controller. 我试图弄清楚如何访问ASP.NET控制器之外的当前登录用户名。
For example I am trying to do this: 例如,我试图这样做:
Track Created and Modified fields Automatically with Entity Framework Code First 使用实体框架代码自动跟踪创建和修改字段
To setup tracking on entities in the DbContext
. 在DbContext
设置对实体的DbContext
。
Here is my ApplicationDbContext
but I keep getting an error saying _httpContextAccessor
is null
: 这是我的ApplicationDbContext
但我一直收到错误,说_httpContextAccessor
为null
:
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
Try injecting the IHttpContextAccessor Interface 尝试注入IHttpContextAccessor接口
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: 你需要在Startup.ConfigureServices
中设置IHttpContextAccessor
才能注入它:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IUserResolverService, UserResolverService>();
and pass that to your repository as needed to record associated username 并根据需要将其传递到您的存储库以记录相关的用户名
@Nkosi has the correct answer but please note that IHttpContextAccessor is now under the namespace: @Nkosi有正确的答案,但请注意IHttpContextAccessor现在在命名空间下:
Microsoft.AspNetCore.Http;
And no longer under: 不再是:
Microsoft.AspNet.Http;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.