【问题标题】:Failed to Inject extended IdentityUser in view in AspNetCore 3.1无法在 AspNetCore 3.1 的视图中注入扩展 IdentityUser
【发布时间】:2021-01-01 12:47:45
【问题描述】:

我创建了一个扩展 IdentityUserApplicationUser。现在我想在视图中显示/隐藏登录和注销。因此,我尝试在_signinPartial.cshtml 视图中注入ApplicationUser,但我收到ApplicationUser 错误。
上面写着the type of namespace ApplicationUser can not be found(are you missing a using directive or an assembly reference)
我在互联网上找到了多个博客,它们的做法与我完全一样。

ApplicationUser.cs

public class ApplicationUser : IdentityUser
{
}

我在Startup.cs 中配置了ApplicationUser,如下所示:

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

我的 _LoginPartial.cshtml 看起来像:

@inject SignInManager<ApplicationUser> signInManager
@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" asp-controller="account" asp-action="index">
        Login
    </a>
  </li>
}

我在_ViewImports.cshtml 视图中导入了Microsoft.AspNetCore.IdentityOAuth2Demo.Models。 当我注入 IdentityUser 而不是 ApplicationUser 时,我可以完美地工作。我可以使用 ApplicationUser 执行其他操作,例如将用户存储在数据库中,为其他目的获取声明。

【问题讨论】:

  • ApplicationUser 是否与_LoginPartial 在同一个命名空间中?如果没有,您可能需要为该命名空间添加 using 语句。
  • 我在 _ViewImports.cshtml 中添加了命名空间。
  • 您说您添加了另外两个命名空间,但不是 ApplicationUser 的一个 - 如果您添加了更多命名空间,请通过将其添加到问题中向我们展示。并且_ViewImports.cshtml 包含在_LoginPartial.cshtml 中。您遗漏了很多信息,无法全面了解问题所在。

标签: c# asp.net-core claims-based-identity


【解决方案1】:

找不到命名空间 ApplicationUser 的类型(您是否缺少 using 指令或程序集引用)。

我已经在 _ViewImports.cshtml 视图中导入了 Microsoft.AspNetCore.Identity 和 OAuth2Demo.Models

要解决此问题,请检查您的ApplicationUser 类是否定义如下。

namespace OAuth2Demo.Models
{
    public class ApplicationUser: IdentityUser
    {
        //...
        //properties here
        //...

请注意,_ViewImports.cshtml 文件可以放在任何文件夹中,在这种情况下它只会应用于该文件夹及其子文件夹中的页面或视图。所以请确保您在正确的_ViewImports.cshtml 文件中添加@using OAuth2Demo.Models

另外,您可以尝试在_signinPartial.cshtml中指定一个完全限定名称,然后检查它是否可以正常工作。

@inject SignInManager<OAuth2Demo.Models.ApplicationUser> signInManager

【讨论】:

  • 其实我后来解决了这个问题。这和你说的原因一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多