Search code examples
c#flurl

Is there a way to write an HTTP request and then execute it at a later time using Flurl?


I am trying to write a Flurl HTTP request that will be executed at a later time.

Here is what I would like to do (C# code):

public async void SomeFunction(string url, object someJson, object someUrlEncodedData)
{
    var exampleRequest1 = url.PostJsonAsync(someJson);
    var exampleRequest2 = url.PostUrlEncodedAsync(someUrlEncodedData);
    //The two lines above instantly get executed, but that's not what I want. 
    //I want them to "wait" until I run some execute command (see below).

    var exampleResult1 = await exampleRequest1.Execute();
    var exampleResult2 = await exampleRequest2.Execute();
    //The "Execute()" function doesn't exist, but what I want is some other 
    //function that sends the request to the URL and then gets the result.
}

Is there a way to do what I wrote in the code above?


Solution

  • Sure. Your requests can be encapsulated in lambdas so their actual execution can be deferred:

    Func<Task<IFlurlResponse>> req1 = () => url.PostJsonAsync(someJson);
    Func<Task<IFlurlResponse>> req2 = () => url.PostUrlEncodedAsync(someUrlEncodedData);
    

    Then simply call them when you need to, e.g. await req1(), or if your execute method needs to be more elaborate you can wrap it in a helper method like this:

    async Task<???> ExecuteAsync(Func<Task<IFlurlResponse>> request) {
      var response = await request();
      // do something with the IFlurlResponse?
    }