尝试在 MVC 视图中显示经过身份验证的用户数据。 使用 ASP.NET 核心 2.1
出现以下错误:
处理请求时发生未处理的异常。 NullReferenceException:对象引用未设置为对象的实例。 AspNetCore.Views_Home_Index.ExecuteAsync(( in Index.cshtml, line 6
使用@Model.id
似乎有问题。从视图中访问经过身份验证的用户的属性的正确方法是什么?
模型/登录模型.cs
using Microsoft.AspNetCore.Identity;
namespace MyProject.Models
{
public class LoginModel
{
[Required]
[UIHint("email")]
public string Email { get; set; }
[Required]
[UIHint("password")]
public string Password { get; set; }
}
}
Views/Account/Login.cshtml
@model LoginModel
<h1>Login</h1>
<div class="text-danger" asp-validation-summary="All"></div>
<form asp-controller="Account" asp-action="Login" method="post">
<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" />
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
</div>
<button class="btn btn-primary" type="submit">Login</button>
</form>
控制者/帐户控制者.cs
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel details, string returnUrl)
{
ApplicationUser user = new ApplicationUser();
if (ModelState.IsValid)
{
user = await userManager.FindByEmailAsync(details.Email);
if (user != null)
{
await signInManager.SignOutAsync();
Microsoft.AspNetCore.Identity.SignInResult result =
await signInManager.PasswordSignInAsync(
user, details.Password, false, false);
if (result.Succeeded)
{
return Redirect(returnUrl ?? "/");
}
}
ModelState.AddModelError(nameof(LoginModel.Email),
"Invalid user or password");
}
return View(details);
}
Views/Home/Index.cshtml
@model ApplicationUser
@if (User.Identity.IsAuthenticated)
{
@Model.Id
}
您可以将UserManager
注入到视图中,并获得相同的结果,而无需将模型传递到视图中:
@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> UserManager
然后做:
@await UserManager.GetUserIdAsync(User)