httpclient异常处理

我在HttpRequestException使用时正在处理PostAsync并且它工作正常,但是当我尝试处理相同的异常时,GetAsync它会抛出TaskCanceledException a task was cancelled很长的超时。我如何GetAsync投掷HttpRequestException?


  public async Task<bool> AddQrCodeToRequest(int projectId, int requestId, string code, string token)

    {

        var data = JsonConvert.SerializeObject(new { code });

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var content = new StringContent(data, Encoding.UTF8, "application/json");

        var result = await client.PostAsync(url, content);

        if (result.IsSuccessStatusCode)

        {

            return true;

        }

        else

        {

            throw new Exception(CreateExceptionDescription(await result.Content.ReadAsStringAsync()));

        }

    }


    public async Task<List<string>> GetUpdatedQrCodesList(Request request, string token)

    {

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var result = await client.GetAsync(url);

        if (result.IsSuccessStatusCode)

        {

            var requestsJson = await result.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<List<string>>(requestsJson);

        }

        else

        {

            throw new Exception(CreateExceptionDescription(await result.Content.ReadAsStringAsync()));

        }

    }

处理岗位


try

{

     string QrCode = result.Text;

     if (await restService.AddQrCodeToRequest(Request, result.Text, Vars.User.Token))

     {

          QrCodes.Add(QrCode);

          await DisplayAlert("Code added", QrCode, "OK");

     }

 }

 catch (Exception ex)

 {

     if (ex is HttpRequestException)

     {

           //network ex handling

     }

     else

     {

           //other handling

     }

}


胡子哥哥
浏览 175回答 1
1回答

慕尼黑8549860

作为解决方法,安装 nuget Plugin.Connectivity 并在执行 GET 之前检查是否有可用的互联网:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!Plugin.Connectivity.CrossConnectivity.Current.IsConnected) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Connection&nbsp;not&nbsp;available &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw&nbsp;new&nbsp;Exception("Not&nbsp;connected."); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP