从 GetAsync 异常访问 HttpRequestMessage

Access HttpRequestMessage from GetAsync exception

如何从 GetAsync 异常中获取 HttpRequestMessage

try {
  using var responseMsg = await httpClient.GetAsync(requestUri);
  var requestMessage = responseMsg.RequestMessage;

} catch (Exception ex) {
  var requestMessage = ????
  Log(requestMessage.Headers);
}

您可以在尝试前手动创建HttpRequestMessage,然后使用HttpClient发送:

HttpRequestMessage httpRequest = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = uri
};

try
{
    HttpClient client = new HttpClient();
    var response = await client.SendAsync(httpRequest);
}
catch(Exception ex)
{
    var x = httpRequest.Headers;
}

在try<->catch之外创建的对象,可以在每个部分使用。