แก้ time out

This commit is contained in:
kittapath 2025-10-18 21:59:27 +07:00
parent 0a42e68b28
commit 4e84e76daf
2 changed files with 28 additions and 9 deletions

View file

@ -37,21 +37,32 @@ namespace BMA.EHR.Recurit.Exam.Service.Core
{
using (var client = new HttpClient())
{
// Set timeout to 30 seconds instead of default 100 seconds
client.Timeout = TimeSpan.FromSeconds(30);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api_key", apiKey);
var _res = await client.GetAsync(apiPath);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var _res = await client.GetAsync(apiPath, cts.Token);
if (_res.IsSuccessStatusCode)
{
var _result = await _res.Content.ReadAsStringAsync();
return _result;
}
return string.Empty;
}
}
catch
catch (TaskCanceledException)
{
throw;
// Log timeout but don't throw - return empty result instead
Console.WriteLine($"API call timed out: {apiPath}");
return string.Empty;
}
catch (Exception ex)
{
// Log other exceptions but don't throw - return empty result instead
Console.WriteLine($"API call failed: {apiPath}, Error: {ex.Message}");
return string.Empty;
}
}
@ -60,10 +71,10 @@ namespace BMA.EHR.Recurit.Exam.Service.Core
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/keycloak/{keycloakId}";
var apiKey = _configuration["API_KEY"];
var apiKey = _configuration["API_KEY"] ?? "";
var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey);
if (apiResult != null)
if (!string.IsNullOrEmpty(apiResult))
{
var raw = JsonConvert.DeserializeObject<GetProfileByKeycloakIdResultLocal>(apiResult);
if (raw != null)
@ -72,9 +83,11 @@ namespace BMA.EHR.Recurit.Exam.Service.Core
return null;
}
catch
catch (Exception ex)
{
throw;
// Log exception but don't throw - return null instead
Console.WriteLine($"GetProfileByKeycloakIdAsync failed for {keycloakId}: {ex.Message}");
return null;
}
}

View file

@ -93,6 +93,12 @@ builder.Services.AddTransient<MailService>();
builder.Services.AddTransient<CMSCandidateService>();
builder.Services.AddTransient<PermissionRepository>();
// Configure HttpClient with timeout
builder.Services.AddHttpClient("default", client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
});
// Add services to the container.
builder.Services.AddControllers(options =>
{
@ -128,11 +134,11 @@ app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapControllers();
app.UseMiddleware<RequestLoggingMiddleware>();
// apply migrations
await using var scope = app.Services.CreateAsyncScope();