Home > Software design >  POST REST Call from C#
POST REST Call from C#

Time:02-12

Trying to do POST rest call to my endpoint, but I want to pass empty body and access token. How can I do that ?

My code is :

using (var client = new HttpClient())
{
  var endPoint = new Uri("my EndPoint");
  var emptyBody = {}; // Getting an error here, not sure if it is right
  var newPostJson = JsonConvert.SerializeObject(emptyBody);
  var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
  var result = client.PostAsync(endPoint, payload).Result.Content.ReadAsStringAsync().Result;
}

Can you tell how Can I pass access token and empty body and do you recommend any other change ? It is my first REST CALL.

CodePudding user response:

First, you should only have one instance of HttpClient in your application so that HTTP connections are correctly managed. That class is thread-safe.

Typically, access tokens are passed as an authorization header, like this:

// Declare HttpClient at the class level
private readonly HttpClient HttpClient = new HttpClient();

// Put this code in your method that needs to make an authenticated request
using var request = new HttpRequestMessage(HttpMethod.Get, myUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await HttpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

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

CodePudding user response:

you pass access token and empty body like this:

using (var httpClient = new HttpClient())
{
  var request = new HttpRequestMessage(HttpMethod.Post, url);
  request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); // add access token
  //request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); if you want to add content

  var response = await httpClient.SendAsync(request);
  var content = await response.Content.ReadAsStringAsync();
}
  • Related