简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM