'Unsupported grant type exception on Flurl POST

I am making a POST to a client authentication endpoint with an encoded auth header and I receive Unsupported grant type exception. Speaking with the client, they say that the request Body should be 'raw' as it appears in POSTMAN. How to set such attribute in Flurl? The same request returns 200 in POSTMAN but 401, Unsupported grant type exception in Flurl.

var bodyText = @"grant_type=password&[email protected]&password=123456A";
   var encodedAuthHeaderText = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{secret}"));
            var response = await Post<ResponseAuth>(bodyText, tokenEndPoint, $"Basic {encodedClientIdSecret}",
                cancellationToken);


   private async Task<T> Post<T>(string bodyText, string resourceEndPoint, string encodedAuthHeaderText,
            CancellationToken cancellationToken)
        {
            var response = default(T);
            try
            {
                response = await $"{_baseEndPoint}{resourceEndPoint}"
                    .WithHeader("Authorization", encodedAuthHeaderText)
                    .WithHeader("Accept", "*/*")
                    .WithHeader("Content-Type", "application/x-www-form-urlencoded")
                    .WithHeader("Accept-Encoding", "gzip, deflate, br")
                    .PostJsonAsync(bodyText, cancellationToken).ReceiveJson<T>();
            }
            catch (FlurlHttpException fe)
            {
                var error = await fe.GetResponseJsonAsync();
                if (fe.StatusCode != null)
                    throw new CounterPartyIppQuoteException((HttpStatusCode) fe.StatusCode, fe,
                        $"Error encountered when making a POST request to {resourceEndPoint} with auth header to IPP");
            }

            return response;
        }


Solution 1:[1]

I think the problem is that you're calling PostJsonAsync. That's telling Flurl to JSON-encode the body, and since you're passing a string instead of an object, it's probably just putting quotes around it, which you don't want. You've specified the Content-Type and formatted the body exactly how you want, so use Flurl's PostStringAsync instead of PostJsonAsync and I think it should work.

As a side-note, you could have used a couple Flurl shortcuts here, namely WithBasicAuth (instead of your first WithHeader), which just takes a username & password and does the encoding for you and adds the header, and PostUrlEncodedAsync which produces that bodyText for you based on a cleaner C# object, and sets the Content-Type header for you. See the docs for examples of both.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Todd Menier