8

Could someone please help me convert this ASP .Net Core example (to be used in my Web Api to consume a management API from Auth0) which uses RestSharp into one using HttpClient?

var client = new RestClient("https://YOUR_AUTH0_DOMAIN/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

I've been struggling... I've got this:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token");

but I'm not sure about the rest... thank you

Nkosi
  • 215,613
  • 32
  • 363
  • 426
Fabricio Rodriguez
  • 3,241
  • 7
  • 40
  • 85

1 Answers1

6

You need to take the request body and create content to post

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token");

var json = "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}"
var content = new StringContent(json, Encoding.UTF8, "application/json");

var response = await client.PostAsync("", content);
Nkosi
  • 215,613
  • 32
  • 363
  • 426
  • 3
    I'm sure you know, but It might be worth mentioning to OP (since there is no structure in the post, its hard to illustrate). Newing up an `HttpClient` instance for every request is a bad idea, its preferable to use a shared `HttpClient` object across a class. – maccettura Jun 20 '17 at 15:03
  • @maccettura yes. I do know and it is worth mentioning. – Nkosi Jun 20 '17 at 15:05