public async Task FindSwaggerDoc(HttpClient client, IEnumerable <string> swaggerSearchPaths, CancellationToken cancellationToken) { ApiDefinitionReader reader = new ApiDefinitionReader(); HashSet <Uri> checkedUris = new HashSet <Uri>(); List <Uri> baseUrisToCheck = new List <Uri>(); if (HasRootUri) { baseUrisToCheck.Add(RootUri); } if (HasBaseUri) { baseUrisToCheck.Add(BaseUri); } foreach (Uri baseUriToCheck in baseUrisToCheck) { foreach (string swaggerSearchPath in swaggerSearchPaths) { if (Uri.TryCreate(baseUriToCheck, swaggerSearchPath, out Uri swaggerUri) && !checkedUris.Contains(swaggerUri)) { var result = await TryGetSwaggerDocAsync(client, swaggerUri, cancellationToken); if (result.Success && reader.CanHandle(result.Document)) { SwaggerUri = swaggerUri; SwaggerDocument = result.Document; return; } checkedUris.Add(swaggerUri); } } } }
private async Task <string?> GetSwaggerDocAsync(HttpClient client, Uri uri, CancellationToken cancellationToken) { try { WriteVerbose(string.Format(Resources.Strings.ApiConnection_Logging_Checking, uri)); HttpResponseMessage?response = await client.GetAsync(uri, cancellationToken).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { _logger.WriteLine(Resources.Strings.ApiConnection_Logging_Cancelled.SetColor(_httpState.ErrorColor)); return(null); } if (response.IsSuccessStatusCode) { WriteLineVerbose(Resources.Strings.ApiConnection_Logging_Found.SetColor(AllowedColors.BoldGreen)); #if NET5_0 string responseString = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); #else string responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); #endif WriteVerbose(Resources.Strings.ApiConnection_Logging_Parsing); ApiDefinitionReader reader = new ApiDefinitionReader(); ApiDefinitionParseResult result = reader.CanHandle(responseString); if (result.Success) { if (result.ValidationMessages.Count == 0) { WriteLineVerbose(Resources.Strings.ApiConnection_Logging_Successful.SetColor(AllowedColors.BoldGreen)); } else { WriteLineVerbose(Resources.Strings.ApiConnection_Logging_SuccessfulWithWarnings.SetColor(_httpState.WarningColor)); foreach (string validationMessage in result.ValidationMessages) { WriteLineVerbose(validationMessage.SetColor(_httpState.WarningColor)); } } return(responseString); } else { WriteLineVerbose(Resources.Strings.ApiConnection_Logging_Failed.SetColor(_httpState.ErrorColor)); return(null); } } else { int statusCode = (int)response.StatusCode; string statusCodeDescription = response.StatusCode.ToString(); WriteLineVerbose($"{statusCode} {statusCodeDescription}".SetColor(_httpState.ErrorColor)); return(null); } } catch (Exception e) { WriteLineVerbose(e.Message.SetColor(_httpState.ErrorColor)); return(null); } finally { WriteLineVerbose(); } }