在Blazor视图中调用异步方法 [英] Calling async methods in Blazor view

查看:381
本文介绍了在Blazor视图中调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器端的blazor客户端,我试图通过登录检查来修改MainLayout剃刀页面.我目前正在使用Blazored进行本地存储保存,并且目前正在查看是否保存了令牌以查看用户是否已登录,但是我不确定如何在razor页面的if语句中翻译该令牌.需要异步方法.

I have a server-side blazor client and I'm trying to modify the MainLayout razor page by having a Login check. I'm currently using Blazored for localstorage saving, and I'm currently using to see if a token is saved to see if user is logged in, however I'm not sure how I translate this in the if statement in razor page because it wants async method.

我的登录检查非常简单,如下所示.

My login check is pretty simple as shown below.

public async Task<bool> IsLoggedIn()
{
    return await m_localStorage.ContainKeyAsync("token").ConfigureAwait(false);
}

在我的Razor页面中,我正在执行此语句检查-由于没有异步修饰符,这显然不起作用

In my Razor page I'm doing this statement check - which obvious doesn't work as there's no async modifier

@if (!await AppState.IsLoggedIn()) //Requires async modifier
{
    <a href="Login" target="_blank">Login</a>
}

我也尝试过使用.Result属性来执行此操作,但是会导致引发异常:(System.AggregateException:'Information:执行了隐式处理程序方法,返回结果Microsoft.AspNetC),带有内部异常-> NullReferenceException:对象引用未设置为对象的实例.

I've also tried doing it using the .Result property, but this results in an exception thrown: (System.AggregateException: 'Information: Executed an implicit handler method, returned result Microsoft.AspNetC)' with an inner-exception -> NullReferenceException: Object reference not set to an instance of an object.

但是从我看到的内容来看,AppState已正确注入,而本地存储似乎已正确注入了AppState.

But from what I can see AppState is injected correctly and the local storage seems to be injected correctly in AppState.

@if (!AppState.IsLoggedIn().Result)
{
    <a href="Login" target="_blank">Login</a>
}

所以我的问题是解决此问题的正确方法是什么,有没有一种方法可以在剃须刀页面中执行异步方法?

So my question is what is the correct way to approach this, is there a way to execute async methods in razor pages?

推荐答案

有没有一种方法可以在剃须刀页面中执行异步方法?

is there a way to execute async methods in razor pages?

否,在Razor组件中没有使用await的方法.这是因为您不能在组件呈现过程中进行异步工作.

No, there isn't a way to use await in a Razor component. This is because you can't do async work as part of the rendering of the component.

顺便说一下,Blazor团队提供的本地存储机制支持数据保护,建议史蒂夫·桑德森(Steve Sanderson)使用它.

Incidentally, the local storage mechanism provided by the Blazor team supports data protection, and is recommended for use by Steve Sanderson.

注意:组件的异步生命周期方法是完成异步工作的位置,因此您可以相应地设计代码,例如,从OnInitializedAsync调用AppState.IsLoggedIn()并将返回的值分配给局部变量可以从您的视图中访问.

Note: The async Lifecycle methods of the component are where async work is done, and thus you can design your code accordingly, as for instance, calling AppState.IsLoggedIn() from OnInitializedAsync, and assigning the returned value to a local variable which can be accessed from your views.

这篇关于在Blazor视图中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆