kofifus
kofifus

Reputation: 19315

Access HttpRequestMessage from GetAsync exception

How can I get HttpRequestMessage from GetAsync exception:

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

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

Upvotes: 0

Views: 343

Answers (1)

GuyKorol
GuyKorol

Reputation: 176

You can manually create the HttpRequestMessage before the try, and then use the HttpClient to send it:

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;
}

The objects created outside the try<->catch, can be used in each part.

Upvotes: 1

Related Questions