将IHttpContextAccessor注入ApplicationDbContext ASP.NET Core 1.0

时间:2016-08-24 19:49:31

标签: c# entity-framework asp.net-core asp.net-core-mvc asp.net-core-1.0

我试图弄清楚如何访问ASP.NET控制器之外的当前登录用户名。

例如我正在尝试这样做:

Track Created and Modified fields Automatically with Entity Framework Code First

设置DbContext

中实体的跟踪

以下是我的ApplicationDbContext,但我一直收到错误消息,指出_httpContextAccessornull

private readonly IHttpContextAccessor _httpContextAccessor;

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

2 个答案:

答案 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;