Luk*_*kas 3 entity-framework asp.net-core
我需要跟踪 net core 2.0 EF 中的数据库更改。这一切都有效,但我不知道如何在 DbContext 中获取 userId 。我需要获取 UserId 来将更改分配给用户。我不能简单地跑步_userManager.GetUserId(HttpContext.User).ToString();
。有什么建议么?在此先感谢您的帮助。
在你的ConfigureServices
方法中Startup.cs
添加:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddEntityFrameworkSqlServer();
Run Code Online (Sandbox Code Playgroud)
该services.AddEntityFrameworkSqlServer()
位将服务解析器添加到您的上下文中,允许您在您的上下文中使用GetService
扩展方法。
然后,在您的上下文中您可以执行以下操作:
var httpContextAccessor = this.GetService<IHttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)
结果可能为 null,特别是如果上下文未在 Web 应用程序中运行(即在迁移期间、控制台应用程序利用您的上下文等)。因此,您应该进行适当的空检查。以下使用 C# 6 的 null 条件运算符:
var userId = httpContextAccessor?.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
Run Code Online (Sandbox Code Playgroud)
然后,userId
将具有当前登录用户的 ID 或为空。
归档时间: |
|
查看次数: |
2524 次 |
最近记录: |