Leo
Leo

Reputation: 63

The input does not contain any JSON tokens (Blazor, HttpClient)

i have an http Get method like below

public async Task<Ricetta> GetRicettaByNome(string nome)
    {
        Ricetta exist = default(Ricetta);
        var ExistRicetta = await appDbContext.Ricetta.FirstOrDefaultAsync(n => n.Nome == nome);
        if(ExistRicetta != null)
        {
            exist = ExistRicetta;
            return exist;
        }
        exist = null;
        return exist;
    }

It gets called by a controller like this:

 [HttpGet("exist/{nome}")]
    public async Task<ActionResult<Ricetta>> GetRicettaByNome(string nome)
    {
        try
        {

            if (string.IsNullOrEmpty(nome))
            {
                return BadRequest();
            }

            var result = await ricetteRepository.GetRicettaByNome(nome);
            if (result != null)
                return result;
            return default(Ricetta);

        }
        catch (Exception)
        {

            return StatusCode(StatusCodes.Status500InternalServerError, "NON HAI INTERNET!");


        }
    }

But when i call my api to get the resposne by an httpclient like this:

 public async Task<Ricetta> GetRicettaByNome(string nome)
    {
        return await httpClient.GetJsonAsync<Ricetta>($"api/Ricette/exist/{nome}");
    }

i got this error: 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.'

Upvotes: 0

Views: 12829

Answers (2)

Nb777
Nb777

Reputation: 2032

Your error exist in your repository part where GetJsonAsync<>. You need to use HttpResponseMessage and check the content before Deserialize for example:

private async ValueTask<T> GetJsonAsync(string ur)
{
  using HttpResponseMessage response = awiat _client.GetAsync(url);
  //some method to validate response
  ValidateResponse(response);
 //then validate your content
 var content = await ValidateContent(response).ReadAsStringAsync();
 return JsonSerializer.Desrialize<T>(content, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
//Here is the method that you need
private HttpContent ValidateContent(HttpResponseMessage response)
 {
    if(string.IsNullOrEmpty(response.Content?.ReadingAsString().Result))
     {
        return response.Content= new StringContent("null",Encoding.UTF8, MediaTypeNames.Application.Json);
     }
   else
     {
      return response.Content;
     }
 }

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273179

This is the expected result when you return null from your API. And default(Ricetta) is the same as null.

You will have to handle this some other way. GetJsonAsync<T>() is convenient shorthand when you know you will always have data. It is not the best option for dealing with null.

You can see (in dev tools) that the status code is 204 (No Content) for null. You can detect that or catch the error from GetJsonAsync.

Upvotes: 4

Related Questions