MVC InvalidOperationException向用户添加角色 [英] MVC InvalidOperationException adding role to user
问题描述
I was following the tutorial on this page, about how to add roles to users programatically in C# MVC. However, when the code executes I get the following error:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=UserId not found.
Source=Microsoft.AspNet.Identity.Core
StackTrace:
at Microsoft.AspNet.Identity.UserManager`2.<AddToRoleAsync>d__83.MoveNext()
--- 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 Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func`1 func)
at Microsoft.AspNet.Identity.UserManagerExtensions.AddToRole[TUser,TKey](UserManager`2 manager, TKey userId, String role)
at SchoolRegistration.Controllers.AccountController.RoleAddToUser(FormCollection collection) in c:\Users\Kyle\Documents\Visual Studio 2013\Projects\SchoolRegistration\SchoolRegistration\Controllers\AccountController.cs:line 98
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
InnerException:
但是我不知道是什么导致了此错误.任何帮助将不胜感激.
But I can't figure out what is causing this error. Any help would be appreciated.
代码:
在我的帐户控制器内:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(FormCollection collection)
{
string UserName = collection["UserName"];
string RoleName = collection["RoleName"];
using (var context = new ApplicationDbContext()) {
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var user2 = new ApplicationUser() { UserName = UserName };
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user2.Id, RoleName);
var account = new AccountController();
//account.UserManager.AddToRole(user.Id, RoleName);
ViewBag.ResultMessage = "Role added successfully.";
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
}
return View("ManageUserRoles");
}
更新:
好吧,在听取了所有人的建议之后,我对代码进行了重新整理,使其看起来如下所示:
Ok so after taking everyone's suggestions I have reworked my code to look like the following:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(FormCollection collection)
{
string UserName = collection["UserName"];
string RoleName = collection["RoleName"];
using (var context = new ApplicationDbContext()) {
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var user2 = UserManager.FindByNameAsync(UserName);
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user2.Id.ToString(),RoleName);
var account = new AccountController();
//account.UserManager.AddToRole(user.Id, RoleName);
ViewBag.ResultMessage = "Role added successfully.";
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
}
return View("ManageUserRoles");
}
奇怪的是,我遇到了完全相同的错误.但是,当我现在将鼠标悬停在参数上时,它实际上具有有效的id而不是null:
The weird thing is, I'm getting the exact same error. However, when I hover over my parameter now, it does in fact have a valid id and not null:
我确实注意到调试时收到的值与数据库中的值不同(这可能是由于哈希安全性造成的?)
I did notice the value I receive when debugging is not the same as the value in the database (this could be due to hashing security?)
DB值:0752a8d8-fb0e-44d9-b8b0-57ccbbff826b
DB Value: 0752a8d8-fb0e-44d9-b8b0-57ccbbff826b
更新2:
对于具有相同问题的ID不匹配的任何人,请尝试使用FindByName方法而不是FindByNameAsync.为我工作!
For anyone having the same problem with the ids not matching, try using the FindByName method instead of FindByNameAsync. Worked for me!
推荐答案
错误消息告诉您问题所在:
The error message is telling you the problem:
找不到Message = UserId.
Message=UserId not found.
您永远不会设置user2.Id,因此当您调用AddToRole时,因为user2.Id为null,所以它找不到要添加角色的用户.
You are never setting user2.Id so when you call AddToRole it cannot find the user to add the role to because user2.Id is null.
您在此处设置了user2: var user2 = new ApplicationUser(){UserName = UserName};
You set user2 here:
var user2 = new ApplicationUser() { UserName = UserName };
然后您在此处引用 user2.Id
,但尚未设置.
Then you reference user2.Id
here but it's not been set.
userManager.AddToRole(user2.Id,RoleName);
尝试先按ID查找用户.
Try finding the user by id first.
这篇关于MVC InvalidOperationException向用户添加角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!