关于c#:HttpClient PostAsync和SendAsync之间的区别

Difference between HttpClient PostAsync and SendAsync

在一个WPF前端的项目上工作,并尝试处理对HttpClient的异步调用,而我一直在四处寻找尝试使PostAsync正常工作,但是它通常似乎死锁,或者在 即使有较大的超时值,后期响应也会超时,并且提琴手中的响应可见。

因此,过了一会儿,我决定尝试使用HttpClient上的其他方法,并且它们起作用了,请首先尝试。 不知道为什么。

我一直使用awaitsasyncs.ConfigureAwait(false)清理到WPF按钮(我认为):

按键:

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

XmlDoc加载:

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

发信息:

1
2
3
4
5
6
7
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",这是我期望的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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,并带有超时消息,而不管超时值如何:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
}

我的端点对其他软件的响应正常,因此我很确定端点是可靠的,我无法理解为何发送响应未被阻止时阻止了响应。


SendAsync可以发出任何http动词请求,具体取决于您设置该属性的方式。 PostAsync和类似的东西只是方便的方法。 这些便捷方法在内部使用SendAsync,这就是为什么当您派生处理程序时,您仅需要覆盖SendAsync而不是所有send方法的原因。

但是,对于另一个问题:
使用SendAsync时,需要创建内容并传递它。 您只发送一个空消息。 500可能意味着api从模型绑定中获取null并将您踢了回来。 就像@约翰评论。