簡體   English   中英

使用 AddHttpContextAccessor 在 ASP.NET Core 3.1 MVC 中獲取當前登錄的用戶 ID

[英]Get currently logged on user id in ASP.NET Core 3.1 MVC with AddHttpContextAccessor

我有一個帶用戶管理的網絡應用程序,主要問題是管理員可以刪除自己,從而使應用程序崩潰。 我有注冊當前用戶 ID 的想法,因此如果當前登錄的用戶試圖刪除自己,它會阻止該操作。

真正的問題在於我不知道我在嘗試獲取下 ID(字符串)時做錯了什么

我添加了services.AddHttpContextAccessor(); Startup類中並添加

private readonly IHttpContextAccessor _httpContextAccessor;

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
        : base(options)
{
        _options = options;
        _httpContextAccessor = httpContextAccessor;
}

在 applicationDbContext 中。

最后在交易用戶的方法所在的類上,我創建了

private readonly IHttpContextAccessor _httpContextAccessor;

然后我嘗試使用這段代碼:

var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

但這會返回空值。 該方法的整個上下文如下:

public async Task DeleteUsuarioAsync(String id)
{
        var strategy = _context.Database.CreateExecutionStrategy();
        await strategy.ExecuteAsync(async () => {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    var user = _context.Users.Where(u => u.Id.Equals(id)).ToList().Last();
                    var _listRoles = await _userRole.getRole(_userManager, _roleManager, id);
                    await _userManager.RemoveFromRoleAsync(user, _listRoles[0].Text);
                    var dataUser = _context.TUsers.Where(u => u.IdUser.Equals(id)).ToList().Last();
                    var idUser = user.Id;
                    var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

                    if (idUser != "25c986cb-d0d3-41aa-aae6-cfcd2279f458")
                    {
                        if (userId == idUser)
                        {
                        }
                        else
                        {
                            _context.Remove(dataUser);
                            _context.SaveChanges();
                            _context.Remove(user);
                            _context.SaveChanges();
                            transaction.Commit();
                        }
                    }
                    else
                    {
                    }

                    //if (idUser == "25c986cb-d0d3-41aa-aae6-cfcd2279f458")
                    //{
                    //}
                    //else
                    //{
                    //    _context.Remove(dataUser);
                    //    _context.SaveChanges();
                    //    _context.Remove(user);
                    //    _context.SaveChanges();
                    //    transaction.Commit();
                    //}
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }
        });
 }

我究竟做錯了什么? 也許還有另一種方法可以防止用戶刪除自己?

編輯:我忘了在控制器上添加方法 inst,但是我創建了一個名為 lusuarios 的類。 似乎我在網上查到的所有教程都是在控制器上完成的。

在我所做的之上,我將IHttpContextAccessor httpContextAccessor添加到類中,如下所示:

public Lusuario(
             UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager,
            RoleManager<IdentityRole> roleManager,
            ApplicationDbContext context,
            IWebHostEnvironment environment,
            IHttpContextAccessor httpContextAccessor)
        {
            _userManager = userManager;
            _roleManager = roleManager;
            _signInManager = signInManager;
            _context = context;
            _environment = environment;
            _userRole = new LUsuariosRoles();
            _uploadimage = new LUploadimage();
            _httpContextAccessor = httpContextAccessor;
        }

然后我不得不將它添加到:HomeController、PerfilController 和我的類 Details 上,就像在所有這些上一樣

 public HomeController(
            UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager,
            RoleManager<IdentityRole> roleManager,
            ApplicationDbContext context,
            IServiceProvider serviceProvider,
            IHttpContextAccessor httpContextAccessor)
        {
            //_serviceProvider = serviceProvider;
            _signInManager = signInManager;
            _usuario = new Lusuario(userManager, signInManager, roleManager, context, null, httpContextAccessor);
        }

然后var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; 不再返回 null,我可以將當​​前登錄的用戶 ID 與被刪除的用戶 ID 進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM