2

我想弄清楚如何訪問ASP.NET控制器以外的當前登錄用戶名。注入IHttpContextAccessor到ApplicationDbContext ASP.NET核心1.0

比如我試圖做到這一點:

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

回答

3

嘗試注入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>(); 

,並根據需要記錄相關聯的用戶名傳遞到你的資料庫

+0

我剛剛在其中看到了一篇文章。我應該只是將它注入到我的ApplicationDbContext中並創建一個私有屬性? –

+0

或多或少。是的 – Nkosi

+0

好的,我打算一直希望它能夠自動注入。 –

3

@Nkosi有正確的答案,但請注意,IHttpContextAccessor現在的命名空間下:

Microsoft.AspNetCore.Http; 

,不再下:

Microsoft.AspNet.Http;