Search code examples
c#asp.netflurl

Flurl API not sending POST request


I need to post webhook info into my database. That is simple enough and I can do that, but I'm having issues updating a line item that has already been inserted into the database. I figured I could change the post I have to a put, but that wouldn't add new entries. I tried to make a solution with this code.

var responseString7 = await url
            .GetAsync()
            .ConfigureAwait(true);

        if (responseString7.IsSuccessStatusCode)
        {
            var responseString = await url
            .WithHeader("Accept", "application/json")
            .PutJsonAsync(new
            {
                trackingNumber = stuff.result.tracking_code,
                EPTrackingStatus = stuff.result.status,
                EPStatusDetails = stuff.result.status_detail,
                EPUpdatedAt = stuff.result.updated_at
            })
            .ReceiveString();
        }
        else
        {
            var responseString3 = await "url you cant see"
                .WithHeader("Accept", "application/json")
                .PostJsonAsync(new
                {
                    trackingNumber = stuff.result.tracking_code,
                    EPTrackingStatus = stuff.result.status,
                    EPStatusDetails = stuff.result.status_detail,
                    EPUpdatedAt = stuff.result.updated_at
                })
                .ReceiveString();

This solution will PUT but not POST. Is there a simpler way to do this?


Solution

  • Flurl behaves differently (by default) than HttpClient with respect to errors. If it hits a non-2xx response, it throws. So it's not getting to your else block because an exception is thrown first. The easiest way to fix your code is to disable that behavior:

    url.AllowAnyHttpStatus().GetAsync();
    

    In the next call, if everything except the verb is the same in the 2 cases (URL, header, data), you might consider simplifying this a bit using Flurl's SendJsonAsync, where you specify the HTTP verb as a variable.

    var method = getResponse.IsSuccessStatusCode ? HttpMethod.Put : HttpMethod.Post;
    
    var responseString3 = await url
        .WithHeader(...)
        .SendJsonAsync(method, new { ... })
        .ReceiveString();