ASP.NET 核心标识 - LoginPartial 在脚手架标识后损坏

ASP.NET Core Identity - LoginPartial broken after scaffolding identity

我从 VS 2017 模板(具有个人用户帐户的 Web 应用程序)创建了一个新项目。

这会将 ASP.NET Core Identity 添加为默认值 UI(使用来自 nuget 的 UI)。

  services
    .AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

有了这个 nuget,一切都按预期工作。特别是 loginPartial,它在用户登录后显示用户名,并在单击注销后立即显示登录按钮。

一旦我构建了布局并应用了更改(根据 the guide in the docs),注销不会删除名称并不再显示登录按钮(在单击注销之后)。只有当我点击 link 到另一个页面时才会发生变化。

当然改配置了(按照指南):

 services
   .AddIdentity<Data.Entities.ApplicationUser, IdentityRole>()
   .AddEntityFrameworkStores<ApplicationDbContext>()
   .AddDefaultTokenProviders();

有谁知道如何解决这个问题或者默认 UI 和脚手架 类 之间有什么区别?

有一个 GitHub issue that describes the exact problem you're running in to. The Razor Class Library (RCL) implementation you were using indirectly before scaffolding has an OnPost implementation in Logout.cshtml.cs that looks like this:

public override async Task<IActionResult> OnPost(string returnUrl = null)
{
    await _signInManager.SignOutAsync();
    _logger.LogInformation("User logged out.");
    if (returnUrl != null)
    {
        return LocalRedirect(returnUrl);
    }
    else
    {
        // This needs to be a redirect so that the browser performs a new
        // request and the identity for the user gets updated.
        return RedirectToPage();
    }
}

正如内联评论所解释的那样,RedirectToPage 需要确保身份在清除后重新加载。如果您查看此方法的脚手架版本,您会发现它在 else 分支中具有以下内容:

return Page();

这就是问题所在。没有重定向,所以没有重新加载身份。您可以通过将其切换为使用 RedirectToPage 来解决问题,如我在上面调用的 RCL 实现中所示。