我正在使用 Entity Framework Core 验证数据库中的用户和密码,但是当我尝试使用多态性声明
var authenticationExt
时,因为该类继承自 authenticationProvider
,调试器会显示:
System.InvalidCastException:无法将类型“Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider”的对象转换为类型“Blazor_Server_App_Login.Extensions.AuthenticationExt”
我从 .NET 7 中的项目中提取了相同的代码。有什么建议吗?
@page "/"
@layout LoginLayout
@inject HttpClient httpClient
@using Blazor_Server_App_Login.Extensions
@using Blazor_Server_App_Login.Shared
@using Blazor_Server_App_Login.Login
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider authenticationProvider
@inject NavigationManager navManager
<div class="row mt-5">
<div class="col-lg-4 offset-lg-4 border">
<div class="mb-3 text-center">
<h3>LOGIN</h3>
</div>
<div class="mb-3">
<label>Email</label>
<input @bind="login.email" class="form-control" />
</div>
<div class="mb-3">
<label>Password</label>
<input @bind="login.password" class="form-control" />
</div>
<div class="mb-3">
<button @onclick="IniciarSesion" class="btn btn-primary">Login</button>
</div>
</div>
</div>
@code {
private UserLogin login = new UserLogin();
private async Task IniciarSesion()
{
var loginResponse = await httpClient.PostAsJsonAsync<UserLogin>("https://localhost:7146/api/User/Login", login);
if (loginResponse.IsSuccessStatusCode)
{
// AuthenticationStateProvider i = new AuthenticationExt();
var sesionUser = await loginResponse.Content.ReadFromJsonAsync<SessionState>();
var autenticationExt = (AuthenticationExt)authenticationProvider;
await autenticationExt.UdateAuthState(sesionUser);
navManager.NavigateTo("/Index");
}
}
}
我在github上检查了你的代码
按照此文档修改服务顺序:
builder.Services.AddServerSideBlazor();
//make sure your AuthenticationStateProvider is registered after basic blazor services registered by `AddServerSideBlazor` method
builder.Services.AddScoped<AuthenticationStateProvider, AuthenticationExt>();
//remove the codes below
//builder.Services.AddScoped<AuthenticationExt>();
自从您在 AuthenticationStateProvider 中注入 ISessionStorage
修改
<component type="typeof(App)" render-mode="ServerPrerendered" />
到
<component type="typeof(App)" render-mode="Server" />
这样您就可以避免 JavaScript 互操作异常,文档相关