HttpClient PostAsync和SendAsync之间的区别

Ian*_*rty 3 c# wpf async-await dotnet-httpclient

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

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

我是干净的一路我的WPF按钮,awaits,asyncs,和.ConfigureAwait(false)(我认为):

按钮:

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

XmlDoc加载:

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

发信息:

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);
}
Run Code Online (Sandbox Code Playgroud)

我立即打电话给我的终点'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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

我的端点正常响应我们的其他软件,所以我很确定端点是可靠的,我无法理解为什么后置响应被阻止,而发送不响应.

JSt*_*ard 12

SendAsync可以根据您设置该属性的方式生成任何http动词请求.PostAsync和类似的只是方便的方法.这些便利方法在SendAsync内部使用,这就是为什么当你派生一个处理程序时,你只需要覆盖SendAsync而不是所有的send方法.

但是对于你的另一个问题: 当你使用时,SendAsync你需要创建内容并传递它.你唯一发送一条空信息.500可能意味着api null从模型绑定中获得并踢回你.就像@John评论的那样.