tre*_*ams 1 c# asp.net-core blazor blazor-server-side blazor-client-side
我正在创建一个 Blazor UI 应用程序来与 API 对话。目前,我正在尝试为此工作获取自定义提供程序,但出现了一些错误。
这是客户 AuthenticationStateProvider
public class APIAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly HttpClient _httpClient;
private readonly ILocalStorageService _localStorage;
public APIAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)
{
_httpClient = httpClient;
_localStorage = localStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var token = await _localStorage.GetItemAsync<string>("authToken");
if (string.IsNullOrWhiteSpace(token))
{
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer", token);
var claims = ParseClaims(token);
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims,"jwt")));
}
}
Run Code Online (Sandbox Code Playgroud)
我在 Startup.cs 文件中的配置服务功能如下所示
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddBlazoredLocalStorage();
services.AddScoped<AuthenticationStateProvider, APIAuthenticationStateProvider>();
services.AddTransient<IAuthRepository, AuthRepository>();
services.AddHttpClient();
}
Run Code Online (Sandbox Code Playgroud)
当我执行时,我收到以下异常
InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendererd. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(long asyncHandle, string identifier, string argsJson)
Microsoft.JSInterop.JSRuntime.InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object[] args)
Microsoft.JSInterop.JSRuntime.InvokeWithDefaultCancellation<T>(string identifier, object[] args)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
Blazored.LocalStorage.LocalStorageService.GetItemAsync<T>(string key)
BookStore_UI.Providers.APIAuthenticationStateProvider.GetAuthenticationStateAsync() in APIAuthenticationStateProvider.cs
Run Code Online (Sandbox Code Playgroud)
我不确定错误是否清楚,这就是错误的真正所在,或者是否还有其他一些我遗漏的潜在步骤。我认为这可能与使用本地存储有关。
该错误与 JS 代码在所有资源加载之前被触发这一事实有关……简而言之。
为了防止它崩溃,我将 Task GetAuthenticationStateAsync() 函数全部包装在 try...catch 中,并且没有抛出异常。
| 归档时间: |
|
| 查看次数: |
1212 次 |
| 最近记录: |