crayden
crayden

Reputation: 2270

Display user data in ASP.NET core MVC

Trying to display authenticated user data in an MVC view. Using ASP.NET Core 2.1

The following error occours:

An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object. AspNetCore.Views_Home_Index.ExecuteAsync() in Index.cshtml, line 6

There seems to be a problem with using @Model.id. What is the correct way of accessing properties of an authenticated user from within the view?

Models/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; }
    }
}

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>

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
}

Upvotes: 0

Views: 3498

Answers (1)

Brendan Green
Brendan Green

Reputation: 11914

You can inject the UserManager into the view, and achieve the same result without having the pass a model into the view:

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

And then doing:

@await UserManager.GetUserIdAsync(User)

Upvotes: 1

Related Questions