簡體   English   中英

在ASP.NET Core MVC中顯示用戶數據

[英]Display user data in ASP.NET core MVC

嘗試在MVC視圖中顯示經過身份驗證的用戶數據。 使用ASP.NET Core 2.1

發生以下錯誤:

處理請求時發生未處理的異常。 NullReferenceException:對象引用未設置為對象的實例。 Index.cshtml第6行中的AspNetCore.Views_Home_Index.ExecuteAsync()

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

控制器/ 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);
}

查看/主頁/ Index.cshtml

@model ApplicationUser
@if (User.Identity.IsAuthenticated)
{
    @Model.Id
}

您可以將UserManager注入到視圖中,而無需將模型傳遞到視圖中即可獲得相同的結果:

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

然后做:

@await UserManager.GetUserIdAsync(User)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM