Ejemplo n.º 1
0
        /// <summary>
        /// Send a POST request to the specified Uri as an asynchronous operation.
        /// </summary>
        /// <param name="api">The api url for the request is sent to.</param>
        /// <param name="parameters">The parameters of the api.</param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task <HttpResponseMessage> PostAsync(string api, IDictionary <string, object> parameters)
        {
            if (parameters is null)
            {
                parameters = new Dictionary <string, object>();
            }

            if (parameters.All(p => p.Value is string))
            {
                return(_http.PostAsync(api, new FormUrlEncodedContent(parameters.ToKeyValuePairs())));
            }

            var content = new MultipartFormDataContent();

            foreach (var(key, value) in parameters)
            {
                switch (value)
                {
                case byte[] bytes:     // bytes
                    content.Add(new ByteArrayContent(bytes), key, OAuthUtility.GenerateNonceString());
                    break;

                case MemoryFileContent memoryContent:     // memory content
                    content.Add(new ByteArrayContent(memoryContent.Content), key, memoryContent.FileName);
                    break;

                case FileInfo file:     // file
                    content.Add(new ByteArrayContent(File.ReadAllBytes(file.FullName)), key, file.Name);
                    break;

                default:
                    content.Add(new StringContent($"{value}"), key);
                    break;
                }
            }

            return(_http.PostAsync(api, content));
        }