未能在AspNetCore 3.1中的视图中注入扩展的IdentityUser


我创建了一个扩展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>();

我的登录部分.shtml看起来像:

@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的类型(是否缺少using指令或程序集引用(。

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

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

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

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

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

@inject SignInManager<OAuth2Demo.Models.ApplicationUser> signInManager

最新更新