Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting code from RestSharp to HttpClient

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

like image 893
Fabricio Rodriguez Avatar asked Jun 20 '17 14:06

Fabricio Rodriguez


People also ask

Does RestSharp use HttpClient?

Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.

Should I use HttpClient or RestSharp?

Some prefer to use HttpClient because it is already built into the framework. So there's no need to add extra bloat to your project. RestSharp, like any library, is easier to use because someone already did the hard work and ironed out the problems gotten along the way.

What is RestSharp?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.

What is RestSharp library?

RestSharp is an open source HTTP client library that makes it easy to consume RESTful services. RestSharp provides a developer friendly interface to work with RESTful services while abstracting the internal intricacies of working with HTTP requests. RestSharp supports both synchronous and asynchronous requests.


1 Answers

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);
like image 195
Nkosi Avatar answered Oct 19 '22 19:10

Nkosi