Beispiel #1
0
        /// <summary>
        /// Creates the entity.
        /// </summary>
        /// <typeparam name="U">Return type.</typeparam>
        /// <typeparam name="T">Type on behalf of which the request is being called.</typeparam>
        /// <param name="path">The path.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        protected async Task <U> CreateEntity <U, T>(string path, T entity, string idempotencyKey = null)
            where U : EntityBase, new()
            where T : EntityPostBase
        {
            var token = await _auth.GetAuthToken();

            if (token != null)
            {
                using var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.access_token}");
                using var httpContent = CreateHttpContent(entity);
                using var request     = new HttpRequestMessage(HttpMethod.Post, path)
                      {
                          Content = httpContent
                      };

                if (!string.IsNullOrWhiteSpace(idempotencyKey))
                {
                    request.Headers.Add(Constants.IDEMPOTENCY_KEY, idempotencyKey);
                }

                using var response = await client
                                     .SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
                                     .ConfigureAwait(false);

                var stream = await response.Content.ReadAsStreamAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(DeserializeJsonFromStream <U>(stream));
                }
                else
                {
                    await HandleApiError(response, stream);
                }
            }
            return(null);
        }