public FilesClient(FilesConfiguration config = null) { if (Instance != null) { log.Info("Files.com Client instance already exists, replacing instance with new one"); } Instance = this; this.config = config; if (this.config == null) { log.Info("FilesConfiguration found in app.config"); this.config = (FilesConfiguration)ConfigurationManager.GetSection(ConfigManagerSectionName); } if (this.config == null) { log.Info("No FilesConfiguration found, using defaults"); this.config = new FilesConfiguration(); } if (this.SessionId != null && this.SessionId.Length > 0) { log.Info("Files.com Client created with Session Id"); } else if (this.ApiKey != null && this.SessionId.Length > 0) { log.Info("Files.com Client created with API Key"); } else { log.Info("Files.com Client created with no preconfigured auth"); } var builder = new HostBuilder() .ConfigureServices((HostExecutionContext, services) => { TimeSpan[] retries = new TimeSpan[this.config.MaxNetworkRetries]; Random rand = new Random(); for (int i = 0; i < retries.Length; i++) { double delay; if (i == 0) { delay = this.config.InitialNetworkRequestDelay; } else if (i == retries.Length - 1) { delay = this.config.MaxNetworkRetryDelay; } else { delay = Math.Min(this.config.InitialNetworkRequestDelay, rand.NextDouble() * this.config.MaxNetworkRetryDelay); } retries[i] = TimeSpan.FromSeconds(delay); } services.AddHttpClient(HttpFilesApi, client => { client.BaseAddress = new Uri(BaseUrl); client.DefaultRequestHeaders.Add(HttpRequestHeader.UserAgent.ToString(), UserAgent); }) .AddTransientHttpErrorPolicy(newBuilder => newBuilder.WaitAndRetryAsync(retries)); services.AddHttpClient(HttpUpload, client => { client.DefaultRequestHeaders.Add(HttpRequestHeader.UserAgent.ToString(), UserAgent); }) .AddTransientHttpErrorPolicy(newBuilder => newBuilder.WaitAndRetryAsync(retries)); services.AddTransient <IFilesApiService, FilesApiService>(); }).UseConsoleLifetime(); host = builder.Build(); }
public async Task <string> SendRequest( string path, HttpMethod verb, Dictionary <string, object> parameters, Dictionary <string, object> options ) { FilesClient filesClient = FilesClient.Instance; if (filesClient == null) { throw new InvalidOperationException("FilesClient instance must be created before sending API requests."); } HttpClient httpClient = _clientFactory.CreateClient(FilesClient.HttpFilesApi); string parsedPath = ParsePathParameters(path, parameters); Uri uri = new Uri(httpClient.BaseAddress, $"api/rest/v1{parsedPath}"); string jsonString = await Task.Run(() => JsonSerializer.Serialize <Dictionary <string, object> >(parameters)); HttpContent httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); var httpRequestMessage = new HttpRequestMessage { Method = verb, RequestUri = uri, Headers = { { HttpRequestHeader.Accept.ToString(), "application/json" }, }, Content = httpContent, }; bool requiresAuth = !(path == "/sessions" && verb == HttpMethod.Post); if (requiresAuth) { if (options.ContainsKey("session_id")) { if (!(options["session_id"] is string)) { throw new ArgumentException("Bad option: session_id must be of type Int64", "options[\"session_id\"]"); } httpRequestMessage.Headers.Add("X-FilesApi-Auth", options["session_id"].ToString()); } else if (options.ContainsKey("api_key")) { if (!(options["api_key"] is string)) { throw new ArgumentException("Bad option: api_key must be of type string", "options[\"api_key\"]"); } httpRequestMessage.Headers.Add("X-FilesApi-Key", (string)options["api_key"]); } else if (filesClient.SessionId != null && filesClient.SessionId.Length > 0) { httpRequestMessage.Headers.Add("X-FilesApi-Auth", filesClient.SessionId.ToString()); } else if (filesClient.ApiKey != null && filesClient.ApiKey.Length > 0) { httpRequestMessage.Headers.Add("X-FilesApi-Key", filesClient.ApiKey); } else { throw new InvalidOperationException($"Authentication required for API request: {verb} {uri}"); } } log.Info($"Sending {verb} request: {uri}"); log.Debug($"content: {jsonString}"); using (HttpResponseMessage response = await httpClient.SendAsync(httpRequestMessage)) { if (!response.IsSuccessStatusCode) { string message = await response.Content.ReadAsStringAsync(); log.Error($"HTTP request failed with code {response.StatusCode}: {message}"); response.EnsureSuccessStatusCode(); } string responseJson = await response.Content.ReadAsStringAsync(); log.Debug(responseJson); return(responseJson); } }