Search code examples
c#flurl

How to write a proper C# GET using Flurl


How do I write my Flurl code to obtain this result, please ?

a. See, I have the header "Authorization" as in this image: enter image description here

b. And I have these values in the body:

enter image description here

With these, my Get obtains this result enter image description here

So in C# I have this:

string clientID = ...;
string clientSecret = ...;
string authCredentials = $"{clientID}:{clientSecret}".Base64Encode(); //This value will be validated.

BearerToken result = serviceURL
   .AppendPathSegment("token")
   .WithHeaders(new
   {
      grant_type = "esslogin",
      ssusername = user,
      sspassword = password
   })
   .WithHeader("Authorization", $"Basic {authCredentials}")
   .GetJsonAsync<BearerToken>().Result;

Alas, I get "One or more errors occurred. (Call failed with status code 400 (Bad Request): GET https://demoservices64..../Login.Secured/token)

I have noticed that I would need to add the grant_type, ssusername, and sspassword into the body and not as params in the header.

How should I write the above using Flurl, please ?

Thank you


Solution

  • There a multiple issues here.

    1. grant_type, ssusername, and sspassword should be passed in the body, not the headers, so don't use WithHeaders.
    2. GetJsonAsync uses the HTTP GET method. But it looks like you want to simulate a form POST, so use PostUrlEncodedAsync instead. And, this method is where you pass the 3 values above. Example here.
    3. Flurl provides a WithBasicAuth method so you don't need to format and encode the Authorization header yourself. Also demonstrated here.
    4. To get the response body's deserialized JSON, you'll need to chain ReceiveJson at the very end, i.e.: .PostUrlEncodedAsync(...).ReceiveJson<BearerToken>();
    5. Don't use .Result. It invites deadlocks. Use await.