asp.net-core - Blazor WebAssembly 和 LocalStorage JSInterop 错误
问题描述
美好的一天,我有一个 Blazor WASM 应用程序,它将调用第三方 API 来获取页面的数据。此 API 需要一个 jwt 令牌,我在登录后检索并存储在 LocalStorage 中。
当我进行第 3 方 API 调用时,我尝试获取令牌以将其添加到 HttpClient 客户端,然后再通过管道发送它。
public async Task<IList<T>> Get(string url)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var client = _client.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer", await GetBearerToken());
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IList<T>>(content);
}
else
{
return null;
}
}
catch (Exception e)
{
return null;
}
}
private async Task<string> GetBearerToken()
{
return await _localStorage.GetItemAsync<string>("authToken");
}
它一直在遇到异常并抱怨以下内容:
{"此时无法发出 JavaScript 互操作调用。这是因为组件正在静态渲染。启用预渲染后,JavaScript 互操作调用只能在 OnAfterRenderAsync 生命周期方法期间执行。"}
有任何想法吗?
页面如下所示:
@page "/authors/"
@inject HttpClient _client
<h3 class="card-title">Index</h3>
<hr />
<br />
@if (Model == null)
{
<LoadingMessage Message="Loading Authors" />
}
else
{
@if (Model.Count < 1)
{
<LoadingMessage Message="There are no authors in the data store.
Click 'Create Author' to Begin " />
}
else
{
<table class="table table-responsive">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var author in Model)
{
<tr>
<td>@author.Firstname</td>
<td>@author.Lastname</td>
<td>
<a href="/authors/view/@author.Id" class="btn btn-primary">
<span class="oi oi-book"></span>
</a>
@*<AuthorizeView Roles="Administrator">*@
<a href="/authors/edit/@author.Id" class="btn btn-warning">
<span class="oi oi-pencil"></span>
</a>
<a href="/authors/delete/@author.Id" class="btn btn-danger">
<span class="oi oi-delete"></span>
</a>
@*</AuthorizeView>*@
</td>
</tr>
}
</tbody>
</table>
}
@code {
private IList<Author> Model;
//Tried this both Synchronous and Asynchronous
protected override void OnInitialized()
{
Model = _client.GetFromJsonAsync<IList<Author>>("api/Authors").Result;
}
}
解决方案
错误信息实际上很清楚。
您的 api 调用是在 OnInitialized() 方法中完成的。那时你的页面还没有完全准备好,但是你的 JSInterop 需要它。
尝试将其移至页面生命周期中的稍后位置。fe 在 OnAfterRenderAsync()
推荐阅读
- ios - 点击图像时显示工具栏 SWIFT
- sql - Bigquery:在 ST_GEOGPOINT 数组中使用 ST_CLUSTERDBSCAN
- mongodb - 图像文件未保存在 MongoDB 中
- firebase-realtime-database - Firebase 数据库 - 使用 REST 请求发送有效负载
- mysql - MYSQL 中是否有与 ORACLE SYS_CONTEXT('USERENV', 'OS_USER') 等价的东西?
- python - 在 Python 中使用 Paramiko 从 top 命令收集输出
- jmeter - Jmeter 采样器 'v1/pages/...' 产生 'java.lang.OutOfMemoryError: Java heap space' 错误
- azure-active-directory - AD 身份验证 - 如何在 MVC dot net 4.6.2 版中刷新令牌
- javascript - 如何在 NodeJs 中创建动态对象名称
- javascript - 根据条件选择和显示值