连接到网络还原上的Azure服务器的HttpClient引发错误-无法连接到远程服务器

时间:2018-11-16 17:35:02

标签: c# azure httpclient

从托管在WPF控件中的httpclient向azure服务器进行查询,然后azure服务器将结果发送回WPF控件。禁用Internet连接并进行postasync查询时,将引发httprequestexception。当恢复互联网连接并进行postaysnc查询时,post async工作正常,如果我再次禁用了Internet连接,并使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);

1 个答案:

答案 0 :(得分:0)

这是预期的行为。如果它无法连接到服务器,则会引发异常。 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
}