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

例如,我正在尝试这样做:

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;
}

最佳答案

尝试注入(inject)IHttpContextAccessor接口(interface)

您甚至可以通过创建服务以仅提供所需信息来进一步对其进行抽象(这是当前登录的用户名)

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才能注入(inject)它:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//OR
//services.AddHttpContextAccessor();
services.AddTransient<IUserResolverService, UserResolverService>();

并将其传递到您的存储库以记录相关的用户名

关于c# - 将IHttpContextAccessor注入(inject)ApplicationDbContext ASP.NET Core 1.0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39131925/

10-10 07:00