Search code examples
c#dotnet-httpclient

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

Solution

  • 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.