我想弄清楚为什么我会收到上述错误。 ASP.NEt框架工作给了我一个很棒的Register类,但我需要创建自己的,因为我需要一个用户注册和一个商家注册到不同的角色,这是我试图在这里设置与商家注册。
所以我只是从帐户控制器复制并粘贴了Register Action。我正确地走这条路吗?而且我无法弄清楚为什么会收到此错误。
[Authorize(Roles = "Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "MerchantID,MerchantName,State,City,StreetAddress,zip,phoneNumber,email, website, Password, ConfirmPassword")] Merchant merchant)
{
if (ModelState.IsValid)
{
var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
//code that I am trying to implement to add to merhcant role
var user = new ApplicationUser { UserName = merchant.email, Email = merchant.email };
var result = await UserManager.CreateAsync(user, merchant.Password);
//Above code is from Register controller
if (result.Succeeded)
{
//System.NullReferenceException: Object reference not set to an instance of an object.
//SO figure out why USerManager is empty. Likely due to MerchantID not being populated yet?
await this.UserManager.AddToRoleAsync(user.Id, merchant.MerchantName);
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
ViewBag.Link = callbackUrl;
return View("DisplayEmail");
}
// AddErrors(result);
//ASP.Net provided code, don't touch.
db.Merchants.Add(merchant);
db.SaveChanges();
return RedirectToAction("Index");
}
答案 0 :(得分:1)
您从未初始化this.UserManager
。由于它是引用类型,因此其默认值为null
。
你初始化一个相同名称的局部变量(这是一个非常令人困惑的事情,例如):
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
但局部变量和类级变量不是一回事。初始化(和使用)类级变量:
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
或使用局部变量:
await UserManager.AddToRoleAsync(user.Id, merchant.MerchantName);