祝你好运,我有一个Blazor WASM应用程序,它将调用第三方API来获取页面的数据。这个API需要一个jwt令牌,我在登录后检索到它并存储在LocalStorage中。
当我进行第三方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互操作调用。这是因为组件正在进行静态渲染。启用预渲染时,只能在OnAfterRenderAsync生命周期方法期间执行JavaScript互操作呼叫。}
有什么想法吗?
页面如下所示:
@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((中