How to Display All Users from ASP.NET Core Identity Database

Retrieve and Display All Users from the ASP.NET Core Identity Database

In this article, I will discuss how to Retrieve and Display All Registered Users from the ASP.NET Core Identity Database. Please read our previous article discussing How to Show or Hide Navigation Menus Based on User Roles in ASP.NET Core Identity.

How do you display all users from the ASP.NET Core Identity Database?

In ASP.NET Core, when working with the Identity framework, displaying all users involves querying the user database using Entity Framework Core. We have already discussed that the application’s registered users are stored in the AspNetUsers identity database table, as shown in the image below.

How do you display all users from the ASP.NET Core Identity Database?

We want to retrieve and display them on a view, as shown in the below image.

Retrieve and Display All Users from the ASP.NET Core Identity Database

Adding ListUsers Action Method in AdministrationController:

Listing all users from the ASP.NET Core Identity database involves querying the database to retrieve user information. The Users property on the UserManager<T> service provides a way to query all users. So, add the following ListUsers() action method to your AdministrationController. Please decorate this action method with the HttpGet verb.

[HttpGet]
public IActionResult ListUsers()
{
    var users = _userManager.Users;
    return View(users);
}
List Users View:

Next, add a view named ListUsers.cshtml within the Views/Administration folder and copy and paste the following code. This view is going to display all the registered users. The model for this view is IEnumerable<ApplicationUser>. If you remember, ApplicationUser is the extended class of IdentityUser.

@model IEnumerable<ApplicationUser>

@{
    ViewBag.Title = "All Users";
}

<h1>All Users</h1>

@if (Model.Any())
{
    <a asp-action="Register" asp-controller="Account"
       class="btn btn-primary mb-3" style="width:auto">
        Add New User
    </a>

    foreach (var user in Model)
    {
        <div class="card mb-3">
            <div class="card-header">
                User Id : @user.Id
            </div>
            <div class="card-body">
                <h5 class="card-title">@user.UserName</h5>
            </div>
            <div class="card-footer">
                <a href="#" class="btn btn-primary">Edit</a>
                <a href="#" class="btn btn-danger">Delete</a>
            </div>
        </div>
    }
}
else
{
    <div class="card">
        <div class="card-header">
            No Users Added Yet
        </div>
    </div>
}

Note: I will show you how to implement the Edit and Delete functionality in our upcoming articles. We added the Edit and Delete buttons to the above view.

Manage Users Navigation Menu:

We want to display the Usera and Roles navigation menus, as shown in the image below.

Manage Users Navigation Menu

Here,

  • In the navigation menu, we want to display the Manage dropdown menu
  • It should contain two options – Users and Roles
  • This dropdown menu should only be displayed if the user is signed in and in the Admin role.
  • We are using Bootstrap 5 for the navigation menu.

So, open the _Layout.cshtml file and then copy and paste the following code into it.

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - ASPNETCoreIdentityDemo</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/ASPNETCoreIdentityDemo.styles.css" asp-append-version="true" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container-fluid">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">

                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="SecureMethod">Secure</a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="NonSecureMethod">Non Secure</a>
                        </li>

                        @if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
                        {
                            <li class="nav-item dropdown">
                                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" 
                                data-bs-toggle="dropdown" aria-expanded="false">
                                    Manage
                                </a>
                                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                                    <a class="dropdown-item" asp-controller="Administration"
                                       asp-action="ListUsers">Users</a>
                                    <a class="dropdown-item" asp-controller="Administration"
                                       asp-action="ListRoles">Roles</a>
                                </ul>
                            </li>
                        }
                    </ul>
                    <ul class="navbar-nav ml-auto">
                        @*If the user is signed-in display Logout link*@
                        @if (SignInManager.IsSignedIn(User))
                        {
                            <li class="nav-item">
                                <form method="post" asp-controller="account" asp-action="logout">
                                    <button type="submit" style="width:auto"
                                            class="nav-link btn btn-link py-0">
                                        Logout @User?.Identity?.Name
                                    </button>
                                </form>
                            </li>
                        }
                        else
                        {
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-controller="account" asp-action="register">
                                    Register
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-controller="account" asp-action="login">
                                    Login
                                </a>
                            </li>
                        }
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2023 - ASPNETCoreIdentityDemo - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)

</body>
</html>

With the above changes in place, run the application, and it should work as expected.

Change in Account Controller

An anonymous user can also register himself as an application user using the Register action method. This method is in the AccountController. So, modify the Register Post action method as follows. If the user is signed in and in the Admin role, the Admin user creates a new user. So, redirect the Admin user to the ListUsers action method of AdministrationController. Please also decorate this method with the AllowAnonymous attribute.

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        // Copy data from RegisterViewModel to ApplicationUser
        var user = new ApplicationUser
        {
            UserName = model.Email,
            Email = model.Email,
            FirstName = model.FirstName,
            LastName = model.LastName
        };

        // Store user data in AspNetUsers database table
        var result = await userManager.CreateAsync(user, model.Password);

        // If user is successfully created, sign-in the user using
        // SignInManager and redirect to index action of HomeController
        if (result.Succeeded)
        {
            // If the user is signed in and in the Admin role, then it is
            // the Admin user that is creating a new user. 
            // So redirect the Admin user to ListUsers action of Administration Controller
            if (signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
            {
                return RedirectToAction("ListUsers", "Administration");
            }

            await signInManager.SignInAsync(user, isPersistent: false);
            return RedirectToAction("index", "home");
        }

        // If there are any errors, add them to the ModelState object
        // which will be displayed by the validation summary tag helper
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
    }

    return View(model);
}

After making the above changes, run the application, log in as an Admin user, and click on the Users menu. This should open the following view.

How to Retrieve and Display All Registered Users from the ASP.NET Core Identity Database

Once you click on the Add New User button, it will open the following page. Please provide valid information and click the Register button, as shown in the image below.

How to Retrieve and Display All Registered Users from the ASP.NET Core Identity Database

Once you provide valid details and click the Register button, the user will be added to the AspNetUsers identity database. Then, it will redirect to the List Users view, as shown in the image below.

How to Retrieve and Display All Registered Users from the ASP.NET Core Identity Database

Best Practices of Users Property of the UserManager Service
  • Performance Considerations: Since Users is an IQueryable, it’s important to remember that the query is not executed until you enumerate over it (like calling .ToList()). 
  • Extending Functionality: If you have extended the ApplicationUser class with additional properties, you can use these in your queries to retrieve or filter users based on these custom properties.
  • Security Considerations: When using the Users property, ensure that you handle the data securely, especially when displaying user information in a user interface, to prevent exposing sensitive information.

In the next article, I will discuss How to Edit Users in ASP.NET Core Identity. In this article, I explain How to Display All Users from the ASP.NET Core Identity Database. I hope you enjoy this article, How to Display All Users from ASP.NET Core Identity Database.

Leave a Reply

Your email address will not be published. Required fields are marked *