不从剃刀组件内执行的异步方法

Async method not executing from within razor component

我有一个服务器端 Blazor 应用,在 'app.razor' 我有:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @(myService.Login())
                </NotAuthorized>
                <Authorizing>
                    <p>Bitte warten...</p>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

这是我的服务:

public class MyService : IMyService
{
    protected readonly HttpClient httpClient;

    public MyService(
        HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public async Task Login()
    {
        await httpClient.GetAsync(loginUrl);
    }
}

服务注册如下:

services.AddHttpClient<IMyService, MyService>(client => 
{ 
    client.BaseAddress = new Uri(someUrl); 
});

但是,我在 运行 上收到以下错误:

System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.Threading.Tasks.VoidTaskResult,App.Services.MyService+d__5]

我做错了什么?

很多...

NotAuthorized 应该是这样的:

 <NotAuthorized>
                @if (!context.User.Identity.IsAuthenticated)
                {
                    <RedirectToLogin />
                }
                else
                {
                    <p>You are not authorized to access this resource.</p>
                }
 </NotAuthorized>

在 if 子句中检查用户是否已通过身份验证。如果不是,您将他重定向到 RedirectToLogin 组件。您不要在此处调用服务方法。

在 else 子句中显示一条消息...这样做是因为可以对用户进行身份验证,但他仍未获得访问资源的授权。

RedirectToLogin.razor

@inject myService myService

Put here html elements to gather the users' credentials with a "Login" 
button, which when clicked, calls myService.Login() method to autenticate the 
user.

@code
{
    // Note: this code sample demonstrate how to login a user when you use 
    // Asp.Net Core Identity. It is not clear what identity system are you using

    protected override void OnInitialized()
    {
        ReturnUrl = "~/" + ReturnUrl;
        NavigationManager.NavigateTo($"Identity/Account/Login?returnUrl= 
                                          {ReturnUrl}", forceLoad:true);
    }

}

注意:此表达式:@(myService.Login()) 的计算结果为 System.Threading.Tasks.VoidTaskResult,这会导致错误。你应该使用 return await httpClient.GetAsync(loginUrl); instead