异步等待HttpClient.PostAsync调用

时间:2015-06-15 18:03:10

标签: c# asynchronous async-await dotnet-httpclient

我正在尝试包含对PostAsync的调用,因此我不必在整个代码库中重新编码调用序列。我遇到的问题是我从调用中分配的HttpResponseMessage与我的方法调用的消费者不同。这是代码:

internal class RestHttpClient
{
    public HttpResponseMessage ResponseMessage = new HttpResponseMessage();

    public async void SendRequest(string adaptiveUri, string xmlRequest)
    {
        using (HttpClient httpClient = new HttpClient())
        {
            StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8);

            try
            {
                ResponseMessage = await httpClient.PostAsync(adaptiveUri, httpConent);
            }
            catch (Exception ex)
            {
                ResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
                ResponseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
            }
        }
    }
}

我正在尝试按如下方式调用该方法:

RestHttpClient restHttpClient = new RestHttpClient();

restHttpClient.SendRequest(adaptiveUri, xmlRequest);

return restHttpClient.ResponseMessage;

当我进行调用时,ResponseMessage对象始终包含Ok状态,即使这不是从PostAsync调用实际返回的内容。

1 个答案:

答案 0 :(得分:13)

你看到这个的原因是因为你的方法是async void,它以“火上浇之忘”的方式执行,所以你看到响应消息的实例返回的值,而不是响应PostAsync

不要公开单个类HttpResponseMessage字段,如果在同一个实例上同时调用它可能是陈旧的。相反,每次都返回一个新实例:

public async Task<HttpResponseMessage> SendRequestAsync(string adaptiveUri, string xmlRequest)
{
    using (HttpClient httpClient = new HttpClient())
    {
        StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8);

        HttpResponseMessage responseMessage = null;
        try
        {
             responseMessage = await httpClient.PostAsync(adaptiveUri, httpConent);
        }
        catch (Exception ex)
        {
            if (responseMessage == null)
            { 
                responseMessage = new HttpResponseMessage();
            }
            responseMessage.StatusCode = HttpStatusCode.InternalServerError;
            responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
        }
        return responseMessage;
    }
}

当你调用它时,正确await它:

return await restHttpClient.SendRequestAsync(adaptiveUri, xmlRequest);