c# How to properly pass HttpRequestMessage in and return HttpRequestMessage out of function without leaks

1.8k Views Asked by At

I'm trying to implement a rest api client in c#. I've created every requests roughly like so:

public async Task<string> CallCreateJob()
{
    HttpRequestMessage requestMessage =
        new HttpRequestMessage(HttpMethod.Post, URL))
    
    requestMessage.Content = new StringContent("some content");

    var getRequestResponse = await RunCallWithAuth(requestMessage);
    string rawResponse = await getRequestResponse.Content.ReadAsStringAsync();
    return rawResponse;
}        

But the important thing is that I would like to wrap around the call with authentication like so:

public async Task<HttpResponseMessage> RunCallWithAuth(HttpRequestMessage requestMessage)
{
    requestMessage.Headers.Add("token", getToken()); //Token assumed to be available.
    HttpResponseMessage firstResponse= await client.SendAsync(requestMessage);
    
    if(firstResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized) {

         if (Refresh()) { //updates token in getToken() call.
            requestMessage.Headers.Add("token", getToken());
            HttpResponseMessage secondResponse = await client.SendAsync(requestMessage);
            if(secondResponse .StatusCode != System.Net.HttpStatusCode.Unauthorized)
                return secondResponse;
            else
                throw new IOException("Could not authenticate");
        }
        else
            throw new IOException("Could not authenticate");
    } else{
        return firstResponse;
    }
}

The part that I'm nervous about is when I pass a HttpRequestMessage in a function and return a HttpResponseMessage object from my function. Since reading up on HttpResponseMessage it seems good practice to use either a using statement or use Dispose when I don't need it anymore. But I don't know what standard c# does when returning an object. Will it move? Or copy? Is there a way to be sure all resources in HttpResponseMessage are properly handled? Same questions apply for passing an object into a function. Are there standard practices on how to do this with http messages?

1

There are 1 best solutions below

0
Dave On

You can just dispose it in the calling function when you're done with it

using (var request = new HttpRequestMessage(HttpMethod.Post, URL))
using (var response = await RunCallWithAuth(request))
{
   // do stuff with the response here
}

Once you return an IDisposable from a function, it then becomes the responsibility of the caller really