HttpClient PostAsync和SendAsync之间的区别

时间:2018-03-07 01:30:26

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

在一个WPF前端的项目上工作,并试图处理对HttpClient的异步调用,我一直在试图让PostAsync工作,但它通常似乎陷入僵局,或者至少post响应超时,即使有大的超时值,也有fiddler中的可见响应。

所以,过了一段时间我决定尝试在HttpClient上使用其他一些方法,然后他们就开始尝试了。不知道为什么。

我一直很干净地使用awaitsasyncs.ConfigureAwait(false)(我认为)我的WPF按钮:

按钮:

private async void Generate_Suite_BTN_Click(object sender, RoutedEventArgs e)
{
    await suiteBuilder.SendStarWs().ConfigureAwait(false);
}

XmlDoc加载:

internal async Task SendStarWs()
{
    var xmlDoc = new XmlDocument();
    xmlDoc.Load("C:\\Temp\\file.xml");
    await StarWSClient.SendStarMessage(xmlDoc).ConfigureAwait(false);
}

的SendMessage:

private static readonly HttpClient Client = new HttpClient {MaxResponseContentBufferSize = 1000000};

public static async Task<STARResult> SendMessage(vars)
{
var response = await SendRequestAsync(url, contentNew, Client).ConfigureAwait(false);
return new STARResult(response, hash);
}

我立即打电话给我的终点'500s',我期待:

var response = await SendRequestAsync(url, contentNew, Client).ConfigureAwait(false);

private static async Task<HttpResponseMessage> SendRequestAsync(string adaptiveUri, StringContent content, HttpClient httpClient)
{
    HttpResponseMessage responseMessage = null;
    try
    {
        responseMessage = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, adaptiveUri)).ConfigureAwait(false);
    }
    catch (Exception ex)
    {
        if (responseMessage == null)
            responseMessage = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.InternalServerError,
                ReasonPhrase = $"SendRequestAsync failed: {ex.Message}"
            };
    }
    return responseMessage;
}

Post变量返回TaskCancellationException,无论超时值如何都带有超时消息:

var response = await PostRequestAsync(url, contentNew, Client).ConfigureAwait(false);

private static async Task<HttpResponseMessage> PostRequestAsync(string adaptiveUri, StringContent content, HttpClient httpClient)
{
    HttpResponseMessage responseMessage = null;
    try
    {
        responseMessage = await httpClient.PostAsync(adaptiveUri, content).ConfigureAwait(false);
    }
    catch (Exception ex)
    {
        if (responseMessage == null)
            responseMessage = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.InternalServerError,
                ReasonPhrase = $"PostRequestAsync failed: {ex.Message}"
            };
    }
    return responseMessage;
}

我的端点正常响应我们的其他软件,因此我非常确定端点是否可靠,我无法理解为什么发布响应被阻止,而发送不响应。

1 个答案:

答案 0 :(得分:8)

SendAsync可以根据您设置该属性的方式发出任何http动词请求。 PostAsync和类似的只是方便的方法。这些便捷方法在内部使用SendAsync,这就是为什么在派生处理程序时只需覆盖SendAsync而不是所有发送方法。

对于您的另一个问题: 使用SendAsync时,您需要创建内容并将其传递。你唯一发送一条空信息。 500可能意味着api从模型绑定中获得了null并踢回了你。正如@John评论的那样。