Last post Aug 19, 2020 06:53 PM by bruce (sqlwork.com)
Aug 19, 2020 03:26 PM|yahya01|LINK
How do I add following headers to an httpclient request?
contentType: "application/json; charset=utf-8",
"Authorization": "Bearer " + apiToken
I have searched for it and there is a lot of information available but it is confusing as to which headings go where.
Aug 19, 2020 03:36 PM|PatriceSc|LINK
Seems you are trying to use https://api.jquery.com/jquery.ajax/ ?
Aug 19, 2020 03:43 PM|yahya01|LINK
I am trying to convert from that to httpclient and I am new to both. My background is Winform.
Aug 19, 2020 06:53 PM|bruce (sqlwork.com)|LINK
first nowadays its recommended to use a single HttpClient(), not create and dispose. as you want to set the token on each request, you use HttpRequestMessage:
// can use injection, httpclient factory or
static private HttpClient _httpClient = new HttpClient();
async TOut AjaxPost<TOut>(string url, object data, string token)
var requestMessage = new HttpRequestMessage
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"),
RequestUri = new Uri(url)
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await _httpClient.SendAsync(requestMessage);
return await response.Content.ReadAsAsync<TOut>();
// handle error