Reputation: 415
For example my rest client looks something like this:
var client = new RestClient("test/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"client_id\":\test123123123\",\"client_secret\":\"fsdfsdhkfsjdhf\",\"audience\":\"https://test.auth0.com/api/v2/\",\"grant_type\":\"client_credentials\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The code above works but I wanted to convert this to HTTP client instead, just not sure how to do it
Upvotes: 0
Views: 2426
Reputation: 143078
The are a lot of examples including official documentation on how to make requests with HttpClient
. For example:
static async Task PostAsJsonAsync(HttpClient httpClient)
{
using HttpResponseMessage response = await httpClient.PostAsJsonAsync(
"todos",
new Todo(UserId: 9, Id: 99, Title: "Show extensions", Completed: false));
response.EnsureSuccessStatusCode()
.WriteRequestToConsole();
var todo = await response.Content.ReadFromJsonAsync<Todo>();
WriteLine($"{todo}\n");
// Expected output:
// POST https://jsonplaceholder.typicode.com/todos HTTP/1.1
// Todo { UserId = 9, Id = 201, Title = Show extensions, Completed = False }
}
Currently the recommended pattern of setting up/creating/consuming HttpClient
's is by using IHttpClientFactory
:
IHttpClientFactory
to implement resilient HTTP requestsIHttpClientFactory
with .NETIHttpClientFactory
in ASP.NET CoreUpvotes: 3