Skip to content

Instantly share code, notes, and snippets.

@vpetkovic
Created October 1, 2019 14:17
Show Gist options
  • Save vpetkovic/d187517793ea5521fb46be406ec3bf38 to your computer and use it in GitHub Desktop.
Save vpetkovic/d187517793ea5521fb46be406ec3bf38 to your computer and use it in GitHub Desktop.
using RestSharp using HTTPClient using WebClient
using RestSharp;
using System.Net;
using System.Net.Http;
public static void useRestSharp(string url)
{
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", APIRequest(), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
public static async void useHTTPClient(string url)
{
var httpClient = new HttpClient();
var request = httpClient.PostAsync(url, new StringContent(APIRequest(), Encoding.UTF8, "application/json")).Result;
var content = await request.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
public static void useWebClient(string url)
{
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
var response = webClient.UploadString(url, APIRequest());
Console.WriteLine(response);
}
// Could be serialized JSON object using json.net or newtonsoft.json
public static string APIRequest()
{
string source = @"C:\Users\vpetkovic\Desktop\NH example.txt";
dynamic obj = new ExpandoObject();
obj.username = "data";
obj.password = "data";
obj.fileName = Path.GetFileName(source);
obj.file = Convert.ToBase64String(File.ReadAllBytes(source));
string apiRequest = "{\r\n \"username\": \"" + obj.username + "\",\r\n \"password\": \"" + obj.password + "\",\r\n \"fileName\": \"" + obj.fileName + "\",\r\n \"file\": \"" + obj.file + "\"\r\n}";
return apiRequest;
}
@danieltadresu
Copy link

Hey, How are you? i write you because i'm looking for a solution of a problem that i have been had since a couple of weeks:

I've been looking for solutions to get the Token provide by Auth0 in c# .net core, but we can not use RestClient, we have to use HttpClient, but when i send a post request to get the token, i get this response:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Sun, 09 May 2021 15:49:23 GMT
  Transfer-Encoding: chunked
  Connection: keep-alive
  Set-Cookie: __cfduid=d6707d7d8f92287df856179f1560c7ef81620575362; expires=Tue, 08-Jun-21 15:49:22 GMT; path=/; domain=.us.auth0.com; HttpOnly; SameSite=Lax; Secure
  Set-Cookie: did=s%3Av0%3A201dbc20-b0de-11eb-b2de-09596368c7c0.yUuhZSxUg806opVapwcfwD19iDw%2FtMT5D%2F82%2FmnTFh4; Max-Age=31557600; Path=/; Expires=Mon, 09 May 2022 21:49:23 GMT; HttpOnly; Secure; SameSite=None
  Set-Cookie: did_compat=s%3Av0%3A201dbc20-b0de-11eb-b2de-09596368c7c0.yUuhZSxUg806opVapwcfwD19iDw%2FtMT5D%2F82%2FmnTFh4; Max-Age=31557600; Path=/; Expires=Mon, 09 May 2022 21:49:23 GMT; HttpOnly; Secure
  CF-Ray: 64cc13d2582e2830-SCL
  Cache-Control: no-store
  Strict-Transport-Security: max-age=31536000
  Vary: Accept-Encoding
  Vary: Origin
  CF-Cache-Status: DYNAMIC
  cf-request-id: 09f36ab77600002830d4a1a000000001
  Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
  ot-baggage-auth0-request-id: 64cc13d2582e2830
  ot-tracer-sampled: true
  ot-tracer-spanid: 14abae4b484b6701
  ot-tracer-traceid: 1353e2132217bff0
  Pragma: no-cache
  X-Auth0-RequestId: 63824ed732c0bd2cbe7b
  X-Content-Type-Options: nosniff
  X-RateLimit-Limit: 30
  X-RateLimit-Remaining: 29
  X-RateLimit-Reset: 1620575364
  Server: cloudflare
  Alt-Svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
  Content-Type: application/json
}

Could you help me to find the token in this response when i send a post request to get my token?, or better, how should i get the token?

Thanks a lot!

@vpetkovic
Copy link
Author

Hi there! Sorry for late reply.

I am not using Auth0 but based on their documentation found here, you can see how to get token based on the authorization flow you are using. You can see what each flow returns as a response, and in a context of your example above response would be stored in
Content: System.Net.Http.HttpConnectionResponseContent

Now you want to deserialize that json response. To achieve that you can use any json (de)serializer but I think using using HttpClient extensions methods in this sense would be the simplest.
You can install it using package manager console Install-Package System.Net.Http.Json and reference it in using statement. Then you will need to replace line 23 with

var response = await request.Content.ReadFromJsonAsync<TokenResponse>();

where TokenResponse is your expected response object

  public class TokenResponse
  {
      // Other properties removed for brevity
      public string access_token { get; set; }
  }

To further simplify future requests you can install IdentityModel package Install-Package IdentityModel and then store retrieved access token like so:

httpClient.SetBearerToken(response.access_token);

Note that this gist is an example for using clients in very short lived console applications hence the class is static, for simplest and quickest of testing. Otherwise, if your use case is different then I suggest you to use IHttpClientFactory to implement resilient HTTP requests

@danieltadresu
Copy link

Hey! thanks a lot, you helped me too much! Hugs from Chile

@vpetkovic
Copy link
Author

Glad I could help 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment