Blazor 在使用 Microsoft Identity Platform 登录后执行代码

Blazor execute code after Login with Microsoft Identity Platform

我通过本教程使用 Microsoft Identity Platform 创建了一个 Blazor Server 应用程序:Blazor Server App Authentication with Azure AD

我的应用应该是公司的一个小工具,纯内部使用。 用户将能够创建和管理事件。 因为它实际上只有少数人使用,所以我计划将用户的姓名或电子邮件地址存储在数据库中,以根据数据库的用户 ID 显示登录人员的正确事件。 不必再处理 Azure AD。

为了实现这一点,每次有人登录时,我都必须查询此电子邮件地址是否已在数据库中,如果不存在,则创建一个新条目。

我的问题是在哪里做这个查询最好。

我的第一个想法是 LoginDisplay.razor

<AuthorizeView>
    <Authorized>
        <a href="MicrosoftIdentity/Account/SignOut">Log out</a>
        Hello, @context.User.Identity?.Name!
    </Authorized>
    <NotAuthorized>
        <a href="MicrosoftIdentity/Account/SignIn">Log in</a>
    </NotAuthorized>
</AuthorizeView>

在这里我可以添加一个在有人登录时执行的方法。 context.User.Identity?.Name 给我我需要的电子邮件地址。 但是如果我把它放在 OnInitializedAsync() 中,每次加载页面时,都会进行检查。

使用此页面上的此代码:ASP.NET Core Blazor authentication and authorization,我可以在其他任何地方获取电子邮件地址。

在哪里查询用户最好?

我认为你可以在 _Host.cshtml.cs:

using Microsoft.AspNetCore.Mvc.RazorPages;

public void Onget(){
 var email= Request.HttpContext.User.Identity.Name;
 //Your query to the database
}