asp.net-corerazorblazorrazor-pagesblazor-webassembly

Blazor render throws error when trying to get data through API


I have this project in .NET 8 web assembly. I have a client and a server.

I am using a Minimal API to first get a string, then I call the server again to parse this string. The string is some custom formatted code, so I made a parser for it.

This is the basic .razor page and code:

@page "/"
@using ClassLibrary.DinersElements
@using MT_Diners_Compare_Engine.Client.Interfaces
@using MT_Diners_Compare_Engine.Client.Services
@rendermode InteractiveWebAssembly

@inject IBlobService blobHelper
@inject ISqlService sqlHelper
@inject IDinersParse dinersParser

<div style="display: flex; gap: 1rem;">
    <div style="flex: 1; border: 1px solid #ccc; padding: 1rem;">
        <h3>MT Service Parsed</h3>
        @MTServiceParsed.tbh.AgencyCurrency
    </div>

    <div style="flex: 1; border: 1px solid #ccc; padding: 1rem;">
        <h3>BC Parsed</h3>
        @* @DisplayDinersFile(BCParsed) *@
    </div>
</div>

@code {
    private string BCDiners = "";
    private string MTServiceDiners = "";
    private DinersFile MTServiceParsed = new();
    private DinersFile BCParsed = new();
    private bool dataIsLoaded = false;

    protected override async Task OnInitializedAsync()
    {
        BCDiners = await blobHelper.GetStrings();
        MTServiceDiners = await sqlHelper.GetLastestDiners();

        MTServiceParsed = await dinersParser.ParseDiners(MTServiceDiners);
        BCParsed = await dinersParser.ParseDiners(BCDiners);
    }
}

Whenever I run the program, it shows fine for 1 second and throws an error

Unhandled error has occurred. Reload

This error is shown in the console:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]

Unhandled exception rendering component: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

System.Text.Json.JsonReaderException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0.

at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan1 bytes) at System.Text.Json.Utf8JsonReader.Read() at System.Text.Json.Serialization.JsonConverter1[[ClassLibrary.DinersElements.DinersFile, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
at System.Text.Json.Serialization.JsonConverter1[[ClassLibrary.DinersElements.DinersFile, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.Serialization.Metadata.JsonTypeInfo1[[ClassLibrary.DinersElements.DinersFile, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ContinueDeserialize(ReadBufferState& bufferState, JsonReaderState& jsonReaderState, ReadStack& readStack)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo1.<DeserializeAsync>d__1[[ClassLibrary.DinersElements.DinersFile, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__121[[ClassLibrary.DinersElements.DinersFile, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at MT_Diners_Compare_Engine.Client.Services.ClientDinersParser.ParseDiners(String dinersFileText) in C:\Users\mg\source\repos\MT-Diners-Compare-Engine\MT-Diners-Compare-Engine\MT-Diners-Compare-Engine.Client\Services\ClientDinersParser.cs:line 13
at MT_Diners_Compare_Engine.Client.Pages.Compare.OnInitializedAsync() in C:\Users\mg\source\repos\MT-Diners-Compare-Engine\MT-Diners-Compare-Engine\MT-Diners-Compare-Engine.Client\Pages\Compare.razor:line 35
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

I've toyed around with the idea that prerendering is destroying it and unloads my data, so I tried to disable it but with no luck. However I do it, be it either component only or global I end up with routing troubles. Could just be me being stupid tbh.

I'm kind of at a loss here.


Solution

  • Resolved it myself

    OnInitializedAsync() was trying to call an API that wasn't async. This resulted in the JSON object I returned was empty when it mattered.

    Before:

    app.MapGet("/api/blob", (IBlobService blobService) => blobService.GetStrings());
    app.MapGet("/api/sql", (ISqlService repo) =>
    {
        var sqlDiners =  repo.GetLastestDiners();
        return sqlDiners is not null
            ? Results.Ok(sqlDiners)
            : Results.NotFound("No customers found.");
    });
    

    After:

    app.MapGet("/api/blob", async (IBlobService blobService) => await blobService.GetStrings());
    app.MapGet("/api/sql", async (ISqlService repo) =>
    {
        var sqlDiners =  await repo.GetLastestDiners();
        return sqlDiners is not null
            ? Results.Ok(sqlDiners)
            : Results.NotFound("No customers found.");
    });