Im trying to create a Login page for my blazor web assembly project. I keep getting this error Microsoft.AspNetCore.Components.ComponentFactory+<>c__DisplayClass9_0.<CreatePropertyInjector>g__Initialize|1(IServiceProvider serviceProvider, IComponent component)
Here's the page that is getting this error
@page "/"
@inject IJSRuntime JSRuntime
@inject IAuthenticationService AuthService
@inject NavigationManager NavManger
@using WebApp.Client.Authentication
<img src="./images/logo.png"/>
@if(showAuthenticationError)
{
<div class="alert alert-danger" role="alert">
@authenticationErrorMessage
</div>
}
<EditForm Model="model" OnInvalidSubmit="ExecuteLogin" class="card card-body bg-light mt-5">
<DataAnnotationsValidator/>
<ValidationSummary/>
<div class="form-group row">
<label for="email" class="col-md-2 col-form-label">Email:</label>
<div class="col-md-10">
<InputText id="email" class="form-conrol" @bind-Value="model.Email" />
<ValidationMessage For="@(() => model.Email)"/>
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-2 col-form-label">Password:</label>
<div class="col-md-10">
<InputText type="password" id="password" class="form-conrol" @bind-Value="model.Password" />
<ValidationMessage For="@(() => model.Password)" />
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="submit" class="btn amr-btn-primary">Login</button>
</div>
</div>
</EditForm>
@code {
private AuthenticationUserModel model = new();
private bool showAuthenticationError = false;
private string authenticationErrorMessage = "";
private async Task ExecuteLogin()
{
showAuthenticationError = false;
var result = AuthService.Login(model);
if(result is not null)
{
NavManger.NavigateTo("/home");
}
else
{
authenticationErrorMessage = "Invalid username or password";
showAuthenticationError = true;
}
}
}
Here's my program page
using Blazored.LocalStorage;using Microsoft.AspNetCore.Components.Authorization;using Microsoft.AspNetCore.Components.WebAssembly.Hosting;using WebApp.Client.Authentication;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
builder.Services.AddScoped<AuthenticationStateProvider, AuthStateProvider>();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddAuthorizationCore();
await builder.Build().RunAsync();
Heres my AuthenticationService Page:
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;
using WebApp.Client.Models;
using System.Net.Http.Headers;
using System.Text.Json;
namespace WebApp.Client.Authentication
{
public class AuthenticationService : IAuthenticationService
{
private readonly HttpClient _client;
private readonly AuthenticationStateProvider _authStateProvider;
private readonly ILocalStorageService _localStorage;
public AuthenticationService(HttpClient client, AuthenticationStateProvider authStateProvider, ILocalStorageService localStorage)
{
_client = client;
_authStateProvider = authStateProvider;
_localStorage = localStorage;
}
public async Task<AuthenticatedUserModel> Login(AuthenticationUserModel userForAuthentication)
{
var data = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", userForAuthentication.UserName),
new KeyValuePair<string, string>("password", userForAuthentication.Password)
});
var authResult = await _client.PostAsync("https://localhost:5001/token", data);
var authContent = await authResult.Content.ReadAsStringAsync();
if (authResult.IsSuccessStatusCode == false)
{
return null;
}
// Deserialize the JSON object
var result = JsonSerializer.Deserialize<AuthenticatedUserModel>(authContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
await _localStorage.SetItemAsync("authToken", result.AccessToken);
((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(result.AccessToken);
// Set the token in the HTTP client
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
return result;
}
public async Task Logout()
{
await _localStorage.RemoveItemAsync("authToken");
((AuthStateProvider)_authStateProvider).NotifyUserLogout();
_client.DefaultRequestHeaders.Authorization = null;
}
}
}
Stacktrace:
Microsoft.AspNetCore.Components.ComponentFactory+<>c__DisplayClass9_0.<CreatePropertyInjector>g__Initialize|1(IServiceProvider serviceProvider, IComponent component)
Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType, IComponentRenderMode callerSpecifiedRenderMode, Nullable<int> parentComponentId)
Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame[] frames, int frameIndex, int parentComponentId)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(ref DiffContext diffContext, int oldStartIndex, int oldEndIndexExcl, int newStartIndex, int newEndIndexExcl)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, int componentId, ArrayRange<RenderTreeFrame> oldTree, ArrayRange<RenderTreeFrame> newTree)
Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, out Exception renderFragmentException)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)
Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.BeginRenderingComponent(IComponent component, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Endpoints.EndpointHtmlRenderer.RenderEndpointComponent(HttpContext httpContext, Type rootComponentType, ParameterView parameters, bool waitForQuiescence)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Components.Endpoints.RazorComponentEndpointInvoker.RenderComponentCore(HttpContext context)
Microsoft.AspNetCore.Components.Endpoints.RazorComponentEndpointInvoker.RenderComponentCore(HttpContext context)
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c+<<InvokeAsync>b__10_0>d.MoveNext()
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
It might be something really dumb that I'm just missing but for the life of me i cant find it. So if someone could help me out that would be really nice.