简体   繁体   English

使用 AddHttpContextAccessor 在 ASP.NET Core 3.1 MVC 中获取当前登录的用户 ID

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

I have a web app with user management, the main problem is that admins can delete themselves and thus crashing the application.我有一个带用户管理的网络应用程序,主要问题是管理员可以删除自己,从而使应用程序崩溃。 I had the idea of getting the current user id registered so if the one that is currently logged tries to delete himself, it blocks that action.我有注册当前用户 ID 的想法,因此如果当前登录的用户试图删除自己,它会阻止该操作。

The real problem resides in that I have no idea of what I'm doing wrong trying to get the under ID (a string)真正的问题在于我不知道我在尝试获取下 ID(字符串)时做错了什么

I added services.AddHttpContextAccessor();我添加了services.AddHttpContextAccessor(); in the Startup class and addedStartup类中并添加

private readonly IHttpContextAccessor _httpContextAccessor;

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

in the applicationDbContext.在 applicationDbContext 中。

Finally on the class where the dealing user's method is, I created最后在交易用户的方法所在的类上,我创建了

private readonly IHttpContextAccessor _httpContextAccessor;

and then I tried to use this snippet of code:然后我尝试使用这段代码:

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

but that returns null.但这会返回空值。 The whole context of the method is as follows:该方法的整个上下文如下:

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

What am I doing wrong?我究竟做错了什么? Perhaps there's another way to prevent the user from deleting himself?也许还有另一种方法可以防止用户删除自己?

Edit : I forgot to add that the method inst on a controller, but a class I created called lusuarios.编辑:我忘了在控制器上添加方法 inst,但是我创建了一个名为 lusuarios 的类。 Seems like all tutorials I checked online all do it on the controller.似乎我在网上查到的所有教程都是在控制器上完成的。

On top of what I did I added IHttpContextAccessor httpContextAccessor to the class like this :在我所做的之上,我将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;
        }

then I had to add it on: HomeController, PerfilController and on my class Details, like this on all of them然后我不得不将它添加到: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);
        }

then var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;然后var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; no longer returned null and I could compare the currently logged user ID with the one that was getting deleted.不再返回 null,我可以将当​​前登录的用户 ID 与被删除的用户 ID 进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC:获取当前登录用户的用户 ID - ASP.NET MVC: Get user id of currently logged in user ASP.NET Core-如何获取当前登录的用户 - ASP.NET Core - How to get currently logged in user 在控制器构造函数ASP.NET 5 MVC6中获取当前登录的用户ID - Get currently logged in user id in controller constructor ASP.NET 5 MVC6 获取asp.net mvc 4中登录用户的id - Get id of the logged in user in asp.net mvc 4 如何获取ASP.NET Core 2中当前登录用户的用户名,而不是应用程序池详细信息 - How to I get the username of the currently logged in user in ASP.NET Core 2, not Application Pool details 在 2 个控制器 ASP.NET Core 3.1 MVC 之间传递 ID - Pass ID between 2 controllers ASP.NET Core 3.1 MVC 用户登录时如何显示特定的 HTML div 元素? ASP.net MVC core 3.1 无实体框架 - How to show specific HTML div element when user is logged in? ASP.net MVC core 3.1 without entity framework ASP.NET 核心 MVC 身份 - 如何查看当前登录的用户? - ASP.NET Core MVC Identity - how to get current logged in user in view? 如何使用 ASP.Net Core Identity 3.1 从 controller 中的登录用户获取 Google 和 Facebook 个人资料图片? - How can I get Google and Facebook profile picture from logged in user in a controller with ASP.Net Core Identity 3.1? 获取ASP.NET Core MVC中当前登录用户的角色 - Get role/s of current logged in user in ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM