Converting code from RestSharp to HttpClient
Asked Answered
O

1

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

Omnifarious answered 20/6, 2017 at 14:39 Comment(0)
I
7

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);
Ionian answered 20/6, 2017 at 14:52 Comment(2)
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.Jochebed
@Jochebed yes. I do know and it is worth mentioning.Ionian

© 2022 - 2024 — McMap. All rights reserved.