0

This is my code using the RestSharp library:

var client = new RestClient("https://example.com/api");
client.Timeout = -1;

var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer token...");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody);

IRestResponse response = await client.ExecuteAsync(request);
// Console.WriteLine(response.Content);
// var res = response.Content;

How can I convert it to HttpClient using best practices?

1
  • It is not a http client , please fix the title Commented Dec 27, 2021 at 18:25

1 Answer 1

2

You can use this:

var client = new HttpClient()
{
    BaseAddress = new Uri("https://example.com"),
    Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds
};

client.DefaultRequestHeaders.Add("Authorization", "Bearer token...");
var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain");

var response = await client.PostAsync("api", body);

var responseString = await response.Content.ReadAsStringAsync();

And for using the HttpClient in the right way I highly recommend to see this link.

Sign up to request clarification or add additional context in comments.

2 Comments

I would recommend specifying the content type in the StringContent constructor rather than adding it as a header.
Yes you are right answer updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.