BlazorWebAssembly-页面刷新时不会调用GetAuthenticationStateAsync()
创始人
2024-12-21 23:00:15
0

在Blazor WebAssembly应用程序中,当页面刷新时,不会自动调用GetAuthenticationStateAsync()方法。因此,需要手动调用此方法来更新身份验证状态。

以下是实现此解决方案的代码示例:

1.在你的页面中添加以下代码:

@inject AuthenticationStateProvider AuthenticationStateProvider

@code{
   protected override async Task OnInitializedAsync()
   {
      var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
      NotifyAuthenticationStateChanged(authState);
   }
}

2.更新Blazor WebAssembly项目中的Program.cs文件,如下所示:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using BlazorApp1.Services;

namespace BlazorApp1
{
  public class Program
  {
    public static async Task Main(string[] args)
    {
      var builder = WebAssemblyHostBuilder.CreateDefault(args);
      builder.RootComponents.Add("app");

      builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

      builder.Services.AddOptions();
      builder.Services.AddAuthorizationCore();

      builder.Services.AddScoped();
      builder.Services.AddScoped();
      builder.Services.AddScoped();

      await builder.Build().RunAsync();
    }
  }
}

3.在上述代码示例中,使用自定义身份验证状态提供程序替换了默认的ProvideAuthenticationState()方法。下面是CustomAuthenticationStateProvider.cs类的代码:

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;

namespace BlazorApp1.Services

{
  public class CustomAuthenticationStateProvider : AuthenticationStateProvider
  {
    public override async Task GetAuthenticationStateAsync()
    {
      // 从服务器获取身份验证令牌

      return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
    }
  }
}

4.最后,在你的Blazor组件中添加授权属性,如下所示:

@page "/dashboard"
@

相关内容

热门资讯

三分钟了解!wepoker俱乐... 三分钟了解!wepoker俱乐部辅助,广西老友玩有破解视频,教你教程(有人有挂)-哔哩哔哩亲,关键说...
关于!wpk透视挂,德普软件,... 关于!wpk透视挂,德普软件,透视教程(有人有挂)-哔哩哔哩1、首先打开德普软件最新版本,在德普软件...
一分钟了解!wepoker轻量... 一分钟了解!wepoker轻量版透视方法,手游字牌辅助脚本工具,新2025教程(有挂讲解)-哔哩哔哩...
热门推荐!拱趴大菠萝可以开挂,... 热门推荐!拱趴大菠萝可以开挂,九九联盟解码器,规律教程(有挂详细)-哔哩哔哩拱趴大菠萝可以开挂辅助器...
玩家必备教程!wepoker可... 玩家必备教程!wepoker可以看底牌,丫丫衡阳字牌2辅助,2025新版教程(讲解有挂)-哔哩哔哩1...
我来教大家!hhpoker德州... 我来教大家!hhpoker德州透视挂,花舍辅助,揭秘攻略(有挂神器)-哔哩哔哩hhpoker德州透视...
分享开挂内幕!pokemmo辅... 分享开挂内幕!pokemmo辅助工具,广西老友玩老师输可以版,透牌教程(有挂透视)-哔哩哔哩1、很好...
攻略讲解!we poker插件... 攻略讲解!we poker插件,wejoker手机版透视脚本,2025新版技巧(有挂方略)-哔哩哔哩...
让我来分享经验!德州之星扫描器... 让我来分享经验!德州之星扫描器,阿拉游戏中心辅助挂教程,曝光教程(有挂辅助)-哔哩哔哩1、阿拉游戏中...
总算了解!德普辅助软件,微乐贵... 总算了解!德普辅助软件,微乐贵阳捉鸡麻将能不能开挂,德州教程(有挂方针)-哔哩哔哩微乐贵阳捉鸡麻将能...