gpt4 book ai didi

c# - EF 核心 : Get Authenticated username in Shadow Properties

转载 作者:太空狗 更新时间:2023-10-29 21:26:14 26 4
gpt4 key购买 nike

作为记录谁输入/更新数据的一部分,我在所有实体中添加了 4 个公共(public)字段(创建者、创建日期、修改者、修改日期)。为此,我使用了多个论坛建议的影子属性功能,包括 https://dotnetcore.gaprogman.com/2017/01/26/entity-framework-core-shadow-properties/

我的问题是如何获取有关经过身份验证的用户的信息?。如果它是一个 Controller ,我可以访问 ApplicationUserManager 但在这种情况下,影子属性在

AppDbContext : IdentityDbContext 类。

这是一个 asp.net core 2 web API 项目。

非常感谢任何建议。谢谢

最佳答案

您可以使用 HttpContext.User.Identity.Name 获取当前用户的名称。您可以使用 IHttpContextAccessor 访问 HttpContext。该接口(interface)应该已经在服务集合中注册。否则,您可以注册它:

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// ...
}

然后,您可以从 DbContext 使用此接口(interface):

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

关于c# - EF 核心 : Get Authenticated username in Shadow Properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48554480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com