locked
GetJsonAsync is throwing an exception in browser RRS feed

  • Question

  • User-2009437049 posted

    Hi,

    I am trying to implement  a small crud in sample application.

    I just created a simple api controller with the  name of Employee and method with http verbs.

    If anyone want to see my code then he can view this at here

    https://prod.liveshare.vsengsaas.visualstudio.com/join?FAAFEA557BEE4BA92B24F48486D744D9F0BF

     [ApiController]
        [Route("[controller]")]
        public class EmployeeController : ControllerBase
        {
            EmployeeRepository objemployee = new EmployeeRepository();   
            [HttpGet]
            [Route("api/Employee/Index")]
            public IEnumerable<Employee> Index()
            {
                return objemployee.GetAllEmployees();
            }
       }

    I am getting an exception  while trying to load data through 

            empList = await Http.GetJsonAsync<Employee[]>("/api/Employee/Index");
    

    Exceptions are mentioned below:

    WASM: Unhandled exception rendering component:
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM: System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0. ---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.ThrowHelper.ThrowJsonReaderException (System.Text.Json.Utf8JsonReader& json, System.Text.Json.ExceptionResource resource, System.Byte nextByte, System.ReadOnlySpan`1[T] bytes) <0x2398fc8 + 0x00020> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.Utf8JsonReader.ConsumeValue (System.Byte marker) <0x1fa7718 + 0x0028e> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.Utf8JsonReader.ReadFirstToken (System.Byte first) <0x1fa6d60 + 0x001ec> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.Utf8JsonReader.ReadSingleSegment () <0x1fa6618 + 0x00234> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.Utf8JsonReader.Read () <0x1fa61d0 + 0x00012> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.JsonSerializer.ReadCore (System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& readStack) <0x1fa5b40 + 0x00062> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:    --- End of inner exception stack trace ---
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.ThrowHelper.ReThrowWithPath (System.Text.Json.ReadStack& readStack, System.Text.Json.JsonReaderException ex) <0x23e6bc8 + 0x00116> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.JsonSerializer.ReadCore (System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& readStack) <0x1fa5b40 + 0x002a8> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.JsonSerializer.ReadCore (System.Type returnType, System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader) <0x1fa4e70 + 0x0003e> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.JsonSerializer.ParseCore (System.String json, System.Type returnType, System.Text.Json.JsonSerializerOptions options) <0x1fa1698 + 0x00086> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at System.Text.Json.JsonSerializer.Deserialize[TValue] (System.String json, System.Text.Json.JsonSerializerOptions options) <0x2398808 + 0x00022> in <81e9245ca982431695a55cc67ffb3b86>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.HttpClientJsonExtensions.GetJsonAsync[T] (System.Net.Http.HttpClient httpClient, System.String requestUri) <0x2270e18 + 0x000fa> in <900d091618e14952821fd2fc9b26598c>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at EMS.Client.Pages.FetchEmployee.OnInitializedAsync () [0x0002a] in C:\ES\Client\Pages\FetchEmployee.razor:51 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x1f4ed10 + 0x00176> in <cc81133ac6304aada69282c517e2b811>:0 
    d.printErr @ blazor.webassembly.js:1
    blazor.webassembly.js:1 WASM:   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x224b4e8 + 0x000f4> in <cc81133ac6304aada69282c517e2b811>:0 

    I have one more question, If my c# function is not in async task and with IActionResult. Do i need to convert my C# as well ?

    Saturday, October 12, 2019 10:10 AM

Answers

  • User-2009437049 posted

    thank you everyone.

    When i am trying to remove route from that function/method then i am receiving the response as expected.

    employees = await Http.GetJsonAsync<Employee[]>("Employee")



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, October 13, 2019 6:16 PM

All replies

  • User475983607 posted

    The error message indicates the API is returning an HTML error message.  I assume you have bugs in the the repository.  Use the Visual Studio debugger to step through the repository code to find the line of code causing the problem.  Also add standard try...catch blocks to catch the error. 

    Saturday, October 12, 2019 11:32 AM
  • User-2009437049 posted

    if you are still there, i can show  you the code through live share.

    i am debugging it, by debugger is already there and control didn't go there  instead browser is not allowing the c# request. before going into , web assembly is throwing an exception. 

    Saturday, October 12, 2019 9:43 PM
  • User564979658 posted

    Found any solutions for this?

    I'm using Blazor Server

    Sunday, October 13, 2019 11:33 AM
  • User-2009437049 posted

    Not yet.

    there are some other ways but i want to use GetJsonAysnc (because it is a light weight function).

    I think either preview 9 have this issue or have changed way to call it.

    Sunday, October 13, 2019 11:47 AM
  • User-2009437049 posted

    thank you everyone.

    When i am trying to remove route from that function/method then i am receiving the response as expected.

    employees = await Http.GetJsonAsync<Employee[]>("Employee")



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, October 13, 2019 6:16 PM
  • User564979658 posted

    Nice to hear it worked!

    But I'm still getting the same error on Blazor Server (not webassembly) using HttpClient. 

    Error: System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ 

    @code {
        WeatherForecast[] forecasts;
    
        protected override async Task OnInitializedAsync()
        {
    
            forecasts = await Http.GetJsonAsync<WeatherForecast[]>("WeatherForecast");
    
        }
    }
    blazor.server.js:15 [2019-10-13T18:45:42.411Z] Error: System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 1 | BytePositionInLine: 0.
     ---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 1 | BytePositionInLine: 0.
       at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
       at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
       at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
       at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
       at System.Text.Json.Utf8JsonReader.Read()
       at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
       --- End of inner exception stack trace ---




    Sunday, October 13, 2019 6:47 PM
  • User-2009437049 posted

    I can help you. do you have a visual studio 2019 ?

    can you initiate the Live shares ?

    this is the controller class at my end.

    WeatherForecastController.cs

    [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
            private static readonly string[] Summaries = new[]
            {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };
    
            private readonly ILogger<WeatherForecastController> logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                this.logger = logger;
            }
    
            [HttpGet]
            public IEnumerable<WeatherForecast> Get()
            {
                var rng = new Random();
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }
           
        }

    and this is the razor view

    @page "/fetchdata"
    @using EMS.Shared
    @inject HttpClient Http
    
    <h1>Weather forecast</h1>
    
    <p>This component demonstrates fetching data from the server.</p>
    
    @if (forecasts == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var forecast in forecasts)
                {
                    <tr>
                        <td>@forecast.Date.ToShortDateString()</td>
                        <td>@forecast.TemperatureC</td>
                        <td>@forecast.TemperatureF</td>
                        <td>@forecast.Summary</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        WeatherForecast[] forecasts;
    
        protected override async Task OnInitializedAsync()
        {
            forecasts = await Http.GetJsonAsync<WeatherForecast[]>("WeatherForecast");
        }
    
    }
    

    and if you still face the same issue then you may need to verify following things.

    Do you have a proper new install of .Net Core 3.0 ?

    Second thing is 

    You need to install blazor preview 9 template.

    Command for installing preview 9.

    dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4

    You can get help from here.

    https://devblogs.microsoft.com/aspnet/asp-net-core-and-blazor-updates-in-net-core-3-0-preview-9/

    Sunday, October 13, 2019 6:51 PM
  • User564979658 posted

    Thanks for the help, but I'm not using WebAssembly.. It works fine on WebAssembly, but not in Blazor Server

    Sunday, October 13, 2019 7:10 PM
  • User-2009437049 posted

    But spenzer, You said you are using GetJsonAsync. this is a client side logic (for web  assembly)

    await Http.GetJsonAsync<WeatherForecast[]>("WeatherForecast");

    In server side, we don't need to call it instead we can call directly.

    When you 'll create a blazor project then you 'll have to choose blazor  server app.

    Sunday, October 13, 2019 7:23 PM
  • User-821857111 posted

    thank you everyone.

    When i am trying to remove route from that function/method then i am receiving the response as expected.

    employees = await Http.GetJsonAsync<Employee[]>("Employee")

    You will also get this error is you have a Web Assembly project that has the ASP.NET Hosted option ticked, and you don't set the Server application as the Startup project.

    Wednesday, October 16, 2019 1:57 PM