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
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.
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.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:Why is this not necessary for
GetBgQuizList
? Because ASP.NET Core serialises complex types like lists to JSON as default.