I am trying to figure out why I am getting the above error. The ASP.NEt frame work gives me a great Register class to use, but I needed to create my own because I need a user to register and a Merchant to register to different roles, which is what I am trying to set up here with the Merchant registration.
So I just copy and pasted the Register Action from the Account controller. AM I going about this the right way? And I can't figure out why I am getting this error.
[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");
}