【发布时间】:2018-08-20 10:52:09
【问题描述】:
当我使用 PostAsync 时,我正在处理 HttpRequestException 并且它工作正常,但是当我尝试在 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
}
}
处理获取(应用程序在超时后崩溃)
try
{
UpdatedQrCodes = await restService.GetUpdatedQrCodesList(Request, Vars.User.Token);
}
catch (Exception ex)
{
if (ex is HttpRequestException)
{
//never thrown
}
else
{
//never also thrown
}
}
【问题讨论】:
-
在你处理 HttpRequestException 的地方添加代码,在你想要的地方添加 main 方法..
-
@AnkurTripathi 添加了
-
如果你想强制一个特定的异常,然后在发出请求的方法中执行 try/catch 并抛出你想要的。不过,我并没有真正看到其中的价值。
-
@Crowcoder 这不是我要找的
-
@VladimirMarchenko 好吧,你不能指望某个异常,因为你希望这样,代码会抛出它抛出的东西。
标签: c# rest xamarin httpclient