[英]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 added在
Startup
类中并添加
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.