Wor*_*ess 7 c# entity-framework asp.net-web-api entity-framework-core .net-core
作为记录谁输入/更新数据的记录的一部分,我在所有实体中添加了4个公共字段(“创建者”,“创建日期”,“修改者”,“修改日期”)。为此,我正在使用多个论坛中建议的阴影属性功能,包括https://dotnetcore.gaprogman.com/2017/01/26/entity-framework-core-shadow-properties/
我的问题是如何获取有关经过身份验证的用户的信息?。如果是控制器,则可以访问ApplicationUserManager,但是在这种情况下,阴影属性位于
AppDbContext:IdentityDbContext 类。
这是一个asp.net core 2 Web API项目。
任何建议都将受到高度赞赏。谢谢
mez*_*tou 10
您可以使用来获取当前用户的名称HttpContext.User.Identity.Name
。您可以访问HttpContext
using IHttpContextAccessor
。此接口应该已经在服务集合中注册。否则,您可以注册它:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以从以下位置使用此接口DbContext
:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
var httpContext = _httpContextAccessor.HttpContext;
if(httpContext != null)
{
var authenticatedUserName = httpContext.User.Identity.Name;
// If it returns null, even when the user was authenticated, you may try to get the value of a specific claim
var authenticatedUserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
// var authenticatedUserId = _httpContextAccessor.HttpContext.User.FindFirst("sub").Value
// TODO use name to set the shadow property value like in the following post: https://www.meziantou.net/2017/07/03/entity-framework-core-generate-tracking-columns
}
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
}
Run Code Online (Sandbox Code Playgroud)