【问题标题】:The input does not contain any JSON tokens (Blazor, HttpClient)输入不包含任何 JSON 令牌(Blazor、HttpClient)
【发布时间】:2021-05-18 10:58:28
【问题描述】:

我有一个如下的 http Get 方法

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;
    }

它被这样的控制器调用:

 [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!");


        }
    }

但是当我调用我的 api 以通过 httpclient 获取响应时:

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

我收到了这个错误: 输入不包含任何 JSON 令牌。当 isFinalBlock 为真时,预期输入以有效的 JSON 令牌开头。路径:$ |行号:0 | BytePositionInLine: 0。'

【问题讨论】:

  • Ricettaclassrecord 还是 struct?如果不是struct,则default(Ricetta) 为空。

标签: httpclient blazor blazor-server-side


【解决方案1】:

这是您从 API 返回 null 时的预期结果。而default(Ricetta)null 相同。

您将不得不以其他方式处理此问题。 GetJsonAsync&lt;T&gt;() 是方便的简写,当您知道您将始终拥有数据时。这不是处理 null 的最佳选择。

您可以看到(在开发工具中)状态代码为 204(无内容)表示 null。您可以从 GetJsonAsync 检测或捕获错误。

【讨论】:

  • 除非Ricetta 是一个结构体。
【解决方案2】:

您的错误存在于GetJsonAsync&lt;&gt; 的存储库部分中。您需要使用HttpResponseMessage 并检查Deserialize 之前的内容例如:

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;
     }
 }

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2020-06-22
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多