从WPF控件中托管的httpclient向azure服务器发出查询,azure服务器将结果发送回WPF控件。当禁用Internet连接并执行postasync查询时,将抛出httprequestexception。当互联网连接恢复并进行postaysnc查询时,post async工作正常,如果我再次禁用互联网连接并使post async抛出异常。一旦重新建立了internet连接,postasync就会抛出httprequest异常。如何解决这个问题。
var httpContent = new StringContent(value, Encoding.UTF8, "application/json");
var queryUri = new Uri(httpClient.BaseAddress, "content/resultvalue");
var response = await httpClient.PostAsync(queryUri, httpContent);
response.EnsureSuccessStatusCode();
var resultJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Result>(resultJson);发布于 2018-11-17 01:46:14
这是预期的行为。如果它无法连接到服务器,则会抛出异常。在Exception Handling标题下的HttpClient.PostAsync文档中对此进行了描述。
如果需要捕获异常,则将其放在try/catch块中,并对该异常执行一些操作。
var httpContent = new StringContent(value, Encoding.UTF8, "application/json");
var queryUri = new Uri(httpClient.BaseAddress, "content/resultvalue");
try {
var response = await httpClient.PostAsync(queryUri, httpContent);
response.EnsureSuccessStatusCode();
var resultJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Result>(resultJson);
} catch (Exception e) {
//report the exception to the user
}https://stackoverflow.com/questions/53342790
复制相似问题