异步HTTP响应消息

时间:2016-06-18 00:08:15

标签: c# asp.net rest asp.net-web-api http-headers

所以这已经有一段时间了。我不确定为什么Visual Studio Debugger会跳过我的Http Response Message步骤。这是我目前的代码:

public async void APIcall()          
{                
    HttpClient httpClient = new HttpClient();
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://xxxx");
    requestMessage.Headers.Add("Accept", "application/json");
    requestMessage.Headers.Add("ContentType", "application/json");
    requestMessage.Headers.Add("RequestMessageGUID", "xxxxxx");
    HttpResponseMessage response = await httpClient.SendAsync(requestMessage);
    string result = await response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
    Console.ReadLine();
}

请提出您的建议和帮助以解决此问题。

1 个答案:

答案 0 :(得分:0)

首先,除非是事件处理程序,否则应避免对async方法执行void。即使您没有返回任何内容,也请使用Task

接下来,您假设您将始终从您的请求中获取内容。

您应首先检查是否有东西可以获得

在void方法上使用async时,异常不会被捕获。这就是为什么它像你说的那样不断跳过的原因。这可能是错误的。

private static HttpClient httpClient = new HttpClient();
public async Task APIcall() {
    try {
        HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://xxxx");
        requestMessage.Headers.Add("Accept", "application/json");
        requestMessage.Headers.Add("ContentType", "application/json");
        requestMessage.Headers.Add("RequestMessageGUID", "xxxxxx");
        HttpResponseMessage response = await httpClient.SendAsync(requestMessage);
        if (response.Content.Headers.ContentLength.GetValueOrDefault() > 0) {
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        } else {
            Console.WriteLine(response.StatusCode);
        }
    } catch(Exception ex) {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}