如何 运行 在 Blazor WebAssembly 登录时编码?

How to run code on login in Blazor WebAssembly?

我试图在每次用户登录时运行一个函数。我尝试的是从 DI 容器中获取 AuthenticationStateProvider 的实例并订阅它的 AuthenticationStateChanged 事件。问题是我的登录页面是使用服务器呈现的 Razor 页面实现的,因此页面会在成功登录后刷新。这意味着我的代码在触发事件后订阅该事件,因此我的处理函数永远不会 运行s。任何人都可以在成功登录后看到 运行 自定义代码的方法吗?

您可以将 AuthorizationService 注入您的组件,然后等待 AuthenticationState 到 运行 代码(如果您的用户已登录)。更多详细信息在 documentation here .

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

<button @onclick="@DoSomething">Do something important</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task DoSomething()
    {
        var user = (await authenticationStateTask).User;

        if (user.Identity.IsAuthenticated)
        {
            // Perform an action only available to authenticated (signed-in) users.
        }
    }
}

您可以将身份验证检查放在组件的 initializedasync 方法或其他合适的地方,而不是 onclick 处理程序。

另一种方法是挂接到 RemoteAuthenticatorViewOnLoginSucceeded 属性,如:

<RemoteAuthenticatorView Action="@Action" OnLogInSucceeded="OnLoginSucceeded" />
@code{
    [Parameter] public string Action { get; set; }

    private void OnLoginSucceeded() 
    {
        // do your stuff here
    }
}

如果您使用的是基于令牌的身份验证 (API),则可以将事件处理程序附加到位于身份验证组件中的 RemoteAuthenticatorView 组件。我认为它有一个在用户登录后立即调用的事件。据我所知,我曾经以这种方式回答过类似的问题,然后将我的答案更改为更有用的内容。试试这个解决方案,如果可行请告诉我们。