C# 在ASP.NET核心MVC中显示用户数据
试图在MVC视图中显示经过身份验证的用户数据。 使用ASP.NET Core 2.1 出现以下错误: 处理请求时发生未处理的异常。 NullReferenceException:对象引用未设置为对象的实例。 Index.cshtml第6行中的AspNetCore.Views\u Home\u Index.ExecuteAsync() 使用C# 在ASP.NET核心MVC中显示用户数据,c#,asp.net-core-mvc,asp.net-identity,C#,Asp.net Core Mvc,Asp.net Identity,试图在MVC视图中显示经过身份验证的用户数据。 使用ASP.NET Core 2.1 出现以下错误: 处理请求时发生未处理的异常。 NullReferenceException:对象引用未设置为对象的实例。 Index.cshtml第6行中的AspNetCore.Views\u Home\u Index.ExecuteAsync() 使用@Model.id似乎有问题。从视图中访问经过身份验证的用户属性的正确方法是什么 模型/LoginModel.cs using Microsoft.AspNet
@Model.id
似乎有问题。从视图中访问经过身份验证的用户属性的正确方法是什么
模型/LoginModel.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; }
}
}
[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);
}
查看/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>
@model ApplicationUser
@if (User.Identity.IsAuthenticated)
{
@Model.Id
}
您可以将
UserManager
插入视图,并在不将模型传递到视图的情况下获得相同的结果:
@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> UserManager
提供可用于重现问题的。如果用户成功登录,则您正在重定向他们。如果由于此原因触发的控制器操作没有将模型传递给视图,则
@model
将为null
。您没有显示HomeController
Index()
方法,但您的异常很明显:您没有将任何模型传递给视图。请理解,您正在尝试执行完全不同的操作:访问您的模型和登录的用户。在ASP.NET Core MVC中,您可以始终使用user
属性中的声明访问您的用户属性。
@await UserManager.GetUserIdAsync(User)