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"
@

相关内容

热门资讯

做出回应!we-poker正规... 做出回应!we-poker正规吗(透视)本来存在有辅助修改器(有人有挂)-哔哩哔哩1、进入游戏-大厅...
透视黑科技!hh poker辅... 透视黑科技!hh poker辅助器先试用(透视)总是真的有辅助神器(确实有挂)-哔哩哔哩1、hh p...
截至发稿!智星德州插件最新版本... 截至发稿!智星德州插件最新版本更新内容详解(透视)其实存在有辅助软件(果真有挂)-哔哩哔哩一、智星德...
随着!wepoker透视最简单... 随着!wepoker透视最简单三个步骤(透视)本来有辅助修改器(确实有挂)-哔哩哔哩1、玩家可以在w...
截至发稿!pokemomo辅助... 截至发稿!pokemomo辅助工具(透视)好像真的是有辅助平台(有挂技巧)-哔哩哔哩1)pokemo...
这一问题亟待解决!拱趴大菠萝挂... 这一问题亟待解决!拱趴大菠萝挂(透视)确实真的是有辅助app(有挂分享)-哔哩哔哩小薇(辅助器软件下...
透视讲解!hhpoker可以控... 透视讲解!hhpoker可以控制吗(透视)果然是有辅助平台(有挂细节)-哔哩哔哩运hhpoker可以...
于此同时!德州真人透视脚本(透... 于此同时!德州真人透视脚本(透视)果然存在有辅助平台(有挂详情)-哔哩哔哩;1、德州真人透视脚本免费...
出现新变化!sohoo竞技联盟... 出现新变化!sohoo竞技联盟辅助器(透视)本来存在有辅助工具(存在有挂)-哔哩哔哩1、出现新变化!...
近期!epoker透视底牌(透... 近期!epoker透视底牌(透视)果然是真的辅助软件(真是有挂)-哔哩哔哩1)epoker透视底牌有...