0

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);
}
kofifus
  • 17,260
  • 17
  • 99
  • 173

1 Answers1

1

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.

GuyKorol
  • 126
  • 5
  • I think you need `()` after new HttpRequestMessage – kofifus Aug 25 '21 at 03:11
  • 1
    @kofifus You don't need to explicitly call the parameterless ctor if you are using object initializer. Please read [the following MSDN article](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer) for more details. – Peter Csala Aug 25 '21 at 08:10
  • 1
    Don't you need `using HttpRequestMessage httpRequest = ...` as `HttpRequestMessage` is disposable ? – kofifus Aug 25 '21 at 21:25
  • 1
    @kofifus you are correct, the object implemets `iDisposeable` so it can be used with `using`, according to [this](https://stackoverflow.com/questions/27715327/when-or-if-to-dispose-httpresponsemessage-when-calling-readasstreamasync) if you do not dispose them manually, the GC will kick in and do it for you. – GuyKorol Aug 26 '21 at 09:32
  • 1
    @kofifus `HttpRequestMessage`'s `Dispose` might be interesting when you have a request body and you want to make sure that stream does not outlive the request object. In case of GET it is not vital to dispose explictly. – Peter Csala Aug 26 '21 at 10:14