Hinsura
6/4/2018 - 1:37 PM

Post To Api As Json

var resultDict = await _messagingManager.SendSms(sms);

//Assert
var smsId = (int)resultDict["Id"];
smsId.ShouldBeGreaterThan(0);
public async Task<Dictionary<string, object>> SendSms(Sms sms)
{
  /* get token */
  var tokenResponse = await GetApiToken();

  /* send sms */
  var uri = _settingManager.GetSettingValue(SettingsManagerConstants.GroupamaSmsApiUri);
  var requestBody = JsonConvert.SerializeObject(sms, Formatting.None);/* serialize class to json string */
  var response = await Extensions.PostToApiAsJson<SmsApiResponse>(uri, requestBody, tokenResponse.AccessToken);

  /* return response */
  response.Result.Add("Success", response.Id > 0);
  response.Result.Add("Id", response.Id);
  response.Result.Add("JsonResponse", JsonConvert.SerializeObject(response, Formatting.None));

  return response.Result;
}
public static async Task<T> PostToApiAsJson<T>(string requestUri, string requestBody, [CanBeNull] string authToken)
{
  var client = new HttpClient();
  client.DefaultRequestHeaders.Clear();
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
  if (authToken != null)
  {
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
  }

  /* prep content - converting string to a byte arary avoids possible bad request (400) issues 
   * related to specials characters in object names eg.: "@type": "job" */
  var content = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(requestBody));
  /* -- or -- */
  //var content = new StringContent(requestBody);
  content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

  /* send post request */
  var response = await client.PostAsync(requestUri, content);
  var responseString = await response.Content.ReadAsStringAsync();

  /* return the json response as the type (class) specified <T> */
  return JsonConvert.DeserializeObject<T>(responseString);
}