【问题标题】:subscribing to Blazor AuthenticationStateChanged订阅 Blazor AuthenticationStateChanged
【发布时间】:2023-02-04 23:53:23
【问题描述】:

我找不到任何有关如何在 blazor 中使用 AuthenticationStateChanged 的​​示例。

我的意图是任何我想对用户登录或注销做出反应的页面我都会使用这些 代码。我找不到任何关于如何实施该事件的示例。我试过的那个只是无限次地开火。

_CustomAuthProvider.AuthenticationStateChanged += AuhtenticationStateChanged;

私人异步无效AuhtenticationStateChanged(任务任务) { //这一直在循环中执行。 }

【问题讨论】:

    标签: blazor-webassembly


    【解决方案1】:

    我知道这很旧,但是当我找到它时我会想要一个答案......

    这是我在 Blazor Web 程序集 (dotnet 6.0) 上使用的代码。这是范围服务的一部分,我可以从我的应用程序中的任何其他地方通过依赖注入访问它。

    注意 await(task) 在事件处理程序中检索状态:

        public AuthenticationService(AuthenticationStateProvider authenticationProvider, IProfileService profileService)
        {
            _profileService = profileService;
            _authenticationProvider = authenticationProvider;
            _authenticationProvider.AuthenticationStateChanged += AuthenticationStateChangedHandler;
    
            // perform initial call into the event handler
            AuthenticationStateChangedHandler(_authenticationProvider.GetAuthenticationStateAsync());
        }
    
        private bool _disposed = false;
    
        public void Dispose()
        {
            if(!_disposed)
            {
                _disposed = true;
                _authenticationProvider.AuthenticationStateChanged -= AuthenticationStateChangedHandler;
            }
        }
    
        public event AuthenticationChanged? AuthenticationChanged;
        public AuthenticationState? AuthenticationState { get; private set; }
    
        private async void AuthenticationStateChangedHandler(Task<AuthenticationState> task)
        {
            AuthenticationState = await (task);
            if(IsAuthenticated)
            {
                // first load profile
                await _profileService.LoadProfile(UserName!);
            }
            else
            {
                await _profileService.EmptyProfile();
            }
            // then update all listening clients, invoke the event
            AuthenticationChanged?.Invoke(AuthenticationState);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 2019-12-29
      • 2019-01-03
      • 2020-03-29
      • 2020-10-11
      相关资源
      最近更新 更多