在ApplicationDbContext中注入IHttpContextAccessor.NET Core 1.0

本文关键字:Core NET IHttpContextAccessor ApplicationDbContext 注入 | 更新日期: 2023-09-27 18:03:45

我想弄清楚如何访问当前登录的用户名之外的ASP。网络控制器。

例如,我想这样做:

使用实体框架代码优先自动跟踪创建和修改的字段

DbContext中的实体上设置跟踪。

这是我的ApplicationDbContext,但我一直得到一个错误说_httpContextAccessornull:

private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
    : base(options)
{
    _httpContextAccessor = httpContextAccessor;
}

在ApplicationDbContext中注入IHttpContextAccessor.NET Core 1.0

尝试注入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";
    }
}

你现在需要在Startup.ConfigureServices中设置IHttpContextAccessor,以便能够注入它:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//OR
//services.AddHttpContextAccessor();
services.AddTransient<IUserResolverService, UserResolverService>();

,并根据需要将其传递给存储库,以记录关联的用户名

@Nkosi有正确的答案,但请注意,IHttpContextAccessor现在在命名空间下:

Microsoft.AspNetCore.Http;

Microsoft.AspNet.Http;