【问题标题】:Display user data in ASP.NET core MVC在 ASP.NET Core MVC 中显示用户数据
【发布时间】:2018-06-24 20:16:22
【问题描述】:

试图在 MVC 视图中显示经过身份验证的用户数据。 使用 ASP.NET Core 2.1

出现以下错误:

处理请求时发生未处理的异常。 NullReferenceException:对象引用未设置为对象的实例。 Index.cshtml 中的 AspNetCore.Views_Home_Index.ExecuteAsync() 第 6 行

使用@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; }
    }
}

查看次数/帐户/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>

Controllers/AccountController.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
}

【问题讨论】:

  • 提供可用于重现问题的minimal reproducible example
  • 如果用户登录成功,您将重定向他们。如果因此触发的控制器操作未将模型传递给视图,则 @Model 将是 null
  • 您没有显示您的 HomeController Index() 方法,但您的例外很明显:您没有将 any 模型传递给您的视图。请理解您正在尝试做完全不同的事情:访问您的模型和登录用户。在 ASP.NET Core MVC 中,您始终可以使用 User 属性中的声明访问您的用户属性。

标签: c# asp.net-core-mvc asp.net-identity


【解决方案1】:

您可以将UserManager 注入到视图中,并且无需将模型传递到视图中即可获得相同的结果:

@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> UserManager

然后做:

@await UserManager.GetUserIdAsync(User)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多