gpt4 book ai didi

asp.net-mvc - 身份 2.1 - 从以前的所有角色中删除,然后添加到特定角色?这样做时调用 UserManager 时还会出错

转载 作者:行者123 更新时间:2023-12-03 18:19:27 32 4
gpt4 key购买 nike

我正在为系统管理员编写一个用户管理器,您可以在其中对用户对象执行各种功能。我目前的困境是我希望能够写出类似的东西

await UserManager.RemoveFromRoleAsync(userID, any);

并将该人从以前的所有角色中删除。

现在我已经编写了这段代码,但它“感觉”很脏,可能会更好。测试时,我还收到一个通用的“对象未设置为对象的实例”错误。

Controller 代码(用户ID和级别从调用页面传入):
var userID = "68790581-d2ae-4bc3-8db3-e4c8f4b0bb9f";
string level = "FullAdmin";

//POST: /Account/MakeAdmin
[HttpPost]
[Authorize(Roles = "SuperAdmin")]
public async Task<ActionResult> MakeAdmin(string userID, string level)
{

if(userID == null || level == null)
{
return View("Error");
}

if (level == "FullAdmin")
{
try
{
await UserManager.RemoveFromRoleAsync(userID, "Admin1");
}

catch { }

try
{
await UserManager.RemoveFromRoleAsync(userID, "ReadOnly");
}

catch { }

//Add to the desired role
try
{
await UserManager.AddToRoleAsync(userID, "SuperAdmin");
}
catch (Exception ex)
{
ViewBag.Exception = ex;
}



return Content("Admin permissions activated");
}

if(level == "ReadOnlyAdmin")
{
try
{
await UserManager.RemoveFromRoleAsync(userID, "SuperAdmin");
}

catch { }

try
{
await UserManager.RemoveFromRoleAsync(userID, "Admin1");
}

catch { }

//Add to the desired role
try
{
await UserManager.AddToRoleAsync(userID, "ReadOnly");
}
catch (Exception ex)
{
ViewBag.Exception = ex;
}


return Content("Read only admin permissions activated");
}

return View();
}

此代码失败 - 这是我的堆栈跟踪:
 Test Name: PostMakeAdmin
Test FullName: Testing.AccountTests.PostMakeAdmin
Test Source: h:\app\Controllers\UnitTest1.cs : line 880
Test Outcome: Failed
Test Duration: 0:00:00.5725984

Result Message:
Test method Testing.AccountTests.PostMakeAdmin threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
Result StackTrace:
at System.Web.HttpContextBaseExtensions.GetOwinEnvironment(HttpContextBase context)
at System.Web.HttpContextBaseExtensions.GetOwinContext(HttpContextBase context)
at app.Controllers.AccountController.get_UserManager() in h:\app\Controllers\AccountController.cs:line 42
at app.Controllers.AccountController.<MakeAdmin>d__c.MoveNext() in h:\app\Controllers\AccountController.cs:line 305
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at app.AccountTests.<PostMakeAdmin>d__d.MoveNext() in h:\app\Controllers\UnitTest1.cs:line 888
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

感谢任何能提供帮助的人!

更新
初始迭代问题已解决。我收到与我的 UserManager 相关的关于“对象引用未设置为对象的实例”的错误。

下面是建立 UserManager 的代码:
 public AccountController()
{
}

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}

public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}

最佳答案

您可以获取用户所属的所有角色,对其进行迭代并删除。

   var user = await UserManager.FindByIdAsync(userId);
await UserManager.RemoveFromRolesAsync(userId, UserManager.GetRoles(userId).ToArray());
await UserManager.AddToRoleAsync(userId, "NewRole");
await UserManager.UpdateAsync(user);

关于asp.net-mvc - 身份 2.1 - 从以前的所有角色中删除,然后添加到特定角色?这样做时调用 UserManager 时还会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30468226/

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