I'm using Entity Framework Core to validate the user and password from the database, but when I try to declare a var authenticationExt
using polymorphism because the class inherited from authenticationProvider
, the debugger says:
System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type 'Blazor_Server_App_Login.Extensions.AuthenticationExt'
I extracted this same code from a project in .NET 7. Any suggestions?
@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");
}
}
}
Full code at: https://github.com/bonfildev/Blazor-Server-App-Login
I checked your codes on github
modify the order of the services follow this document :
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>();
Since you injected ISessionStorage in your AuthenticationStateProvider
modify
<component type="typeof(App)" render-mode="ServerPrerendered" />
to
<component type="typeof(App)" render-mode="Server" />
so that you could avoid JavaScript interop exception,see document related