我正在关注来自 NDC Oslo 的示例应用程序,即此应用程序:https ://github.com/SteveSandersonMS/presentation-2019-06-NDCOslo/tree/master/demos/MissionControl 。这将 JWT 实现为身份验证和授权。但是,当我尝试将代码的实现复制到服务器端 Blazor 时,当我尝试从下面描述的本地存储中获取存储的 JWT 令牌时出现错误“
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.
这是我的 Blazor 代码
protected override async Task OnInitializedAsync()
{
var token = await TokenProvider.GetTokenAsync();
Branches = await Http.GetJsonAsync<List<BranchDto>>(
"vip/api/lookup/getbranches",
new AuthenticationHeaderValue("Bearer", token));
}
错误来自
public async Task<string> GetTokenAsync()
{
//Code Omitted for brevity
//This line of code is equivalent to the IJSRuntime.Invoke<string>("localstorage.getitem","authToken")
//change to use Blazore.LocalStorage.
var token = await _localStorageService.GetItemAsync<string>("authToken");
return token;
}
我尝试在OnAfterRenderAsync(bool firstRender)上执行代码,错误消失了,但绑定到 API 请求的网格没有显示。API 请求必须填充必须为OnInitializedAsync的网格的数据源。有什么解决方法吗?
更新! 我移动了代码 OnAfterRenderAsync 并添加了 StateHasChanged 方法,我得到了所需的行为。我忘记了用于渲染的连接是 signalR 连接。