Search code examples
c#flurl

Close Flurl connection asap on POST


How to close the connection asap when requests finish? Does Flurl close connection automatically on FlurResponse Dispose?

var fileContent = new FileContent("myfile");
using (var result = await url.WithHeader("Content-Type","application/octet-stream").PostAsync(fileContent))
                {
                   
                }

Solution

  • Make your own FlurlClient object, and call Dispose() or wrap it in a using().

    The way you're currently doing it, Flurl will create its own client.

    Flurl.Http adheres to this guidance by default. Fluent methods like this will create an HttpClient lazily, cache it, and reuse it for every call to the same host*:

    var data = await "http://api.com/endpoint".GetJsonAsync();
    

    So instead, make your own

    using (var client = new FlurlClient("mybaseurl"))
    {
        // anything you want to do with it.
        await url
            .WithClient(client)
            // ... others
            .PostAsync();
    
        // or without the extension method
        await client
            .Request(url)
            // ... others
            .PostAsync();
    }
    

    See the documentation about lifetime