如何使用身份从 SQL 服务器获取用户信息

How get User Information from SQL Server with identity

我正在使用 ASP.NET 核心 MVC。我想从具有身份的 SQL 服务器获取用户信息。

这是我的 AdminController:

private ApplicationDbContext _application;
public AdminController (ApplicationDbContext application)
{
    _application = application;
}

public IActionResult ListUsers()
{
    return View(_application.Users.ToList());
}

我的看法:

{
    <td>@Html.DisplayNameFor(model => model.Id)</td>
}

但它告诉我错误。

"InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[Microsoft.AspNetCore.Identity.IdentityUser]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable1[WebAppMVC.ApplicationUser]'.

您的 ApplicationUser 继承自 identityUser?

检查视图响应是否与视图模型相同

这是一个工作演示,请检查您的差异并进行修改:

DbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

控制器

public class HomeController : Controller
{
    private readonly ApplicationDbContext _dbcontext;

    public HomeController( ApplicationDbContext dbcontext)
    {
        _dbcontext = dbcontext;
    }

    public IActionResult ListUsers()
    {
        return View(_dbcontext.Users.ToList());
    }
}

查看

@model IEnumerable<MVCIdentityDemo3_1.Models.ApplicationUser>

<table class="table">
  <thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.UserName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th></th>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in Model)
    {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Id)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
            <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
            <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
        </td>
    </tr>
    }
  </tbody>
</table>