skip to Main Content

I have two similar calls on a Blazor page:

private async void SelectQuiz()
    {
        List<String>? ls  = await httpClient.GetFromJsonAsync<List<String>>("api/BgQuizAnswer/GetBgQuizList");
        String?       txt = await httpClient.GetFromJsonAsync<String>      ("api/BgQuizAnswer/GetHello");

The first call works fine while the second one fails.

        [HttpGet]
        [Route("GetBgQuizList")]
        public ActionResult<List<String>> GetBgQuizList()
        {
            return _bgQuizAnswerService.GetBgQuizList();
        }
        [HttpGet]
        [Route("GetHello")]
        public ActionResult<String> GetHello()
        {
            return "Hello";
        }

Here’s the start of the error messages I get when I inspect the page:

Unhandled Exception:
System.Text.Json.JsonException: ‘H’ is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
—> System.Text.Json.JsonReaderException: ‘H’ is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.

Note that the ‘H’ is the first letter of the return string. If I change ‘Hello’ to ‘Jello’, the error complains about ‘J’.

3

Answers


  1. Chosen as BEST ANSWER

    Replacing
    return "Hello";
    with
    return JsonSerializer.Serialize("Hello");
    works.

    Replacing
    String? txt = await httpClient.GetFromJsonAsync ("api/BgQuizAnswer/GetHello");
    with
    String? txt = await httpClient.GetStringAsync("api/BgQuizAnswer/GetHello");
    also works.


  2. A valid JSON should be enclosed with {...} (braces) which represents an object or [...] (square brackets) which represents an array.

    The API for the second HttpClient call returns a string.

    You should use GetStringAsync to get the string value.

    String? txt = await httpClient.GetStringAsync("api/BgQuizAnswer/GetHello");
    
    Login or Signup to reply.
  3. You’re trying to retrieve content as JSON, but your API doesn’t return it as JSON. Thus you need to change your GetHello method to correct this:

            [HttpGet]
            [Route("GetHello")]
            public ActionResult<String> GetHello()
            {
                return Json("Hello");
            }
    

    Why is this not necessary for GetBgQuizList? Because ASP.NET Core serialises complex types like lists to JSON as default.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search