Goal: Simple blazor app in which, after the user has logged in and their authentication state is confirmed, I call the backend to load some user data.
Process: I launch the app locally from Visual Studio and call an [Authorized] Blazor server endpoint.
Problem: Whatever [Authorized] endpoint I call first, no matter what it is, throws an error with "{"'<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."}" because instead of returning a JSON payload, it's returning a log in page.
The funny bit is that if I refresh the page, every endpoint returns the data it's supposed to just fine.
Code
The first endpoint it calls is immediately in the MainLayout.razor page, UserService.LoadCurrentUserAsync:
@inject AuthenticationStateProvider AuthenticationStateProvider @inject IUserService UserService // ... protected override async Task OnInitializedAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity is not null && user.Identity.IsAuthenticated) { try { await UserService.LoadCurrentUserAsync(); } catch (Exception ex) { await Console.Error.WriteLineAsync("Error with LoadCurrentUserAsync: " + ex.Message); } } }UserService.LoadCurrentUserAsync could only be called if the user was already authenticated. Here is LoadCurrentUserAsync:
public async Task LoadCurrentUserAsync() { CurrentUser = await apiService.GetAsync<DtoCurrentUser>("api/users/me"); if (CurrentUser is not null) { CurrentUser.Initials = GetInitials(CurrentUser?.FullName); Company = CurrentUser?.Companies.FirstOrDefault(); } }