Good Day, I have a Blazor WASM application that will call a third party API to get data for a page. This API requires a jwt token, which I have retrieved after the login and stored in LocalStorage.
When I make the 3rd Party API call, I attempt to fetch the token to add it to the HttpClient client, before send it across the pipe.
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");
}
It is consistently hitting the exception and complaining about the following:
{"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."}
Any Ideas?
The Page looks like this:
@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;
}
}
The error message is actually quite clear.
Your api call is done in the OnInitialized() method. At that point your page is not fully ready yet, but your JSInterop needs that.
Try moving it to a later point in the page lifecylce. fe in OnAfterRenderAsync()