我有一个服务器端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。AsyncTaskMethodBuilder
1+AsyncStateMachineBox
1[System.Threading.Tasks.VoidTaskResult,App.Services.MyService+d__5]
我做错了什么?
lot…
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