An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object. AspNetCoreGeneratedDocument.Areas_Identity_Views_Account_SendCode.ExecuteAsync()
I met this problem when sending authentication code when logging in
The code is:
AccountController
using System;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using AppMvc.Net.ExtendMethods;
using AppMvc.Net.Areas.Identity.Models.AccountViewModels;
using AppMvc.Net.ExtendMethods;
using AppMvc.Net.Models;
using AppMvc.Net.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace AppMvc.Net.Areas.Identity.Controllers
{
[Authorize]
[Area("Identity")]
[Route("/Account/[action]")]
public class AccountController : Controller
{
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ILogger<AccountController> _logger;
public AccountController(
UserManager<AppUser> userManager,
SignInManager<AppUser> signInManager,
IEmailSender emailSender,
ILogger<AccountController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_logger = logger;
}
// GET: /Account/Login
[HttpGet("/login/")]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost("/login/")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserNameOrEmail, model.Password, model.RememberMe, lockoutOnFailure: true);
// Tìm UserName theo Email, đăng nhập lại
if ((!result.Succeeded) && AppUtilities.IsValidEmail(model.UserNameOrEmail))
{
var user = await _userManager.FindByEmailAsync(model.UserNameOrEmail);
if (user != null)
{
result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, lockoutOnFailure: true);
}
}
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "Tài khoản bị khóa");
return View("Lockout");
}
else
{
ModelState.AddModelError("Không đăng nhập được.");
return View(model);
}
}
return View(model);
}
// POST: /Account/LogOff
[HttpPost("/logout/")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User đăng xuất");
return RedirectToAction("Index", "Home", new { area = "" });
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public IActionResult RegisterConfirmation()
{
return View();
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("ErrorConfirmEmail");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("ErrorConfirmEmail");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "ErrorConfirmEmail");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
returnUrl ??= Url.Content("~/");
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Lỗi sử dụng dịch vụ ngoài: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
// Cập nhật lại token
await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["ProviderDisplayName"] = info.ProviderDisplayName;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
// Input.Email
var registeredUser = await _userManager.FindByEmailAsync(model.Email);
string externalEmail = null;
AppUser externalEmailUser = null;
// Claim ~ Dac tinh mo ta mot doi tuong
if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
{
externalEmail = info.Principal.FindFirstValue(ClaimTypes.Email);
}
if (externalEmail != null)
{
externalEmailUser = await _userManager.FindByEmailAsync(externalEmail);
}
if ((registeredUser != null) && (externalEmailUser != null))
{
// externalEmail == Input.Email
if (registeredUser.Id == externalEmailUser.Id)
{
// Lien ket tai khoan, dang nhap
var resultLink = await _userManager.AddLoginAsync(registeredUser, info);
if (resultLink.Succeeded)
{
await _signInManager.SignInAsync(registeredUser, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
else
{
// registeredUser = externalEmailUser (externalEmail != Input.Email)
/*
info => user1 ([email protected])
=> user2 ([email protected])
*/
ModelState.AddModelError(string.Empty, "Không liên kết được tài khoản, hãy sử dụng email khác");
return View();
}
}
if ((externalEmailUser != null) && (registeredUser == null))
{
ModelState.AddModelError(string.Empty, "Không hỗ trợ tạo tài khoản mới - có email khác email từ dịch vụ ngoài");
return View();
}
if ((externalEmailUser == null) && (externalEmail == model.Email))
{
// Chua co Account -> Tao Account, lien ket, dang nhap
var newUser = new AppUser()
{
UserName = externalEmail,
Email = externalEmail
};
var resultNewUser = await _userManager.CreateAsync(newUser);
if (resultNewUser.Succeeded)
{
await _userManager.AddLoginAsync(newUser, info);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);
await _userManager.ConfirmEmailAsync(newUser, code);
await _signInManager.SignInAsync(newUser, isPersistent: false);
return LocalRedirect(returnUrl);
}
else
{
ModelState.AddModelError("Không tạo được tài khoản mới");
return View();
}
}
var user = new AppUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
// Update any authentication tokens as well
await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
return LocalRedirect(returnUrl);
}
}
ModelState.AddModelError(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
//
// GET: /Account/ForgotPassword
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Dùng mã Authenticator
if (model.SelectedProvider == "Authenticator")
{
return RedirectToAction(nameof(VerifyAuthenticatorCode), new { ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _emailSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
model.ReturnUrl ??= Url.Content("~/");
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return LocalRedirect(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
//
// GET: /Account/VerifyAuthenticatorCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyAuthenticatorCode(bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyAuthenticatorCodeViewModel { ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyAuthenticatorCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyAuthenticatorCode(VerifyAuthenticatorCodeViewModel model)
{
model.ReturnUrl ??= Url.Content("~/");
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return LocalRedirect(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Mã sai.");
return View(model);
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AppMvc.Net.Areas.Identity.Models.AccountViewModels
{
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<SelectListItem> Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
}
View: SendCode.cshtml
@using Microsoft.AspNetCore.Mvc.ModelBinding
@model SendCodeViewModel
@{
ViewData["Title"] = "Gửi mã xác thực";
}
<h1>@ViewData["Title"].</h1>
<form asp-controller="Account" asp-action="SendCode" asp-route-returnurl="@Model.ReturnUrl" method="post"
class="form-horizontal" role="form">
<input asp-for="RememberMe" type="hidden" />
<div class="row">
<div class="col-md-8">
Mã xác thực gửi tới:
<select asp-for="SelectedProvider" asp-items="Model.Providers"></select>
<button type="submit" class="btn btn-success btn-sm">Gửi</button>
</div>
</div>
</form>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
I tried model.Providers in SendCode (post method) and it has no value but in SendCode func in get method it has value
NullReferenceException: Object reference not set to an instance of an object. AspNetCoreGeneratedDocument.Areas_Identity_Views_Account_SendCode.ExecuteAsync()
Then main reason is because your ModelState is invalid and you return View without model.
Then let me explain further thing for you:
From .NET 6 the non-nullable property must be required, otherwise the ModelState will be invalid.
Form submit will submit the input value and bind the value in backend by matching the name attribute(<input name="xxx" />
) with property name. So that your post method here only can receive RememberMe,SelectedProvider and ReturnUrl except Providers
.
ICollection<SelectListItem> Providers
is a complex type property which cannot be stored like simple type in input element.
You can avoid required validation by adding ?
:
public class SendCodeViewModel
{
public string SelectedProvider { get; set; }
public ICollection<SelectListItem>? Providers { get; set; }
public string ReturnUrl { get; set; }
public bool RememberMe { get; set; }
}
Although the Providers
is no need to be validated. The other property also contains possibilities to be null and fail for validation. So it is also necessary to make sure set the Providers
value in HttpPost SendCode action because you need return SendCode view:
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (!ModelState.IsValid)
{
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
model.Providers = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(model);
}