为了账号安全,请及时绑定邮箱和手机立即绑定

httpclient异常处理

httpclient异常处理

C#
胡子哥哥 2021-12-05 14:51:19
我在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     }}
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

作为解决方法,安装 nuget Plugin.Connectivity 并在执行 GET 之前检查是否有可用的互联网:

            if (!Plugin.Connectivity.CrossConnectivity.Current.IsConnected)
            {
                // Connection not available
                throw new Exception("Not connected.");
            }


查看完整回答
反对 回复 2021-12-05
  • 1 回答
  • 0 关注
  • 174 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信