Converting code from RestSharp to HttpClient

Fabricio Rodriguez picture Fabricio Rodriguez · Jun 20, 2017 · Viewed 7.9k times · Source

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

Answer

Nkosi picture Nkosi · Jun 20, 2017

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