with this configuration, when I run on localhost both projects at the same time it works as expected (communicating with API to Web project and get data). even if I run the API in Docker and web in localhost, also it works(communicating with API to Web project and get data). But when I run API and Web Project in Docker, individually work, (Works) API:http://localhost:6969/swagger/index.html (Works) WEB:http://localhost:8080/Account/Login but they can not communicate with API to Web project and web app can not get results, and gets an error on logger: Connection refused. (Why?) help me to resolve it, I use Docker-Compose file to run both projects on Docker.
builder.Services.AddCors(options => { options.AddPolicy(“AllowWebApp”, builder => { builder .WithOrigins(“http://localhost:5759”, “http://localhost:8080”, “https://localhost:44361”) // Replace with the URL of your web app .AllowAnyMethod() .AllowAnyHeader(); }); });
API
`
builder.Services.AddSingleton<IAuthorizationHandler, PostViewRequirementHandler>();
builder.Services.Configure(builder.Configuration.GetSection(“Kestrel”));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMediatR(cfg => { cfg.RegisterServicesFromAssembly(typeof(Program).Assembly); });
var app = builder.Build();
Log.Information("Application Starting...");
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseCors("AllowWebApp");
app.UseAuthorization();
app.MapControllers();
Log.Information("API Application Running...");
app.Run();`
Web app
`
public async Task<Post[]> GetPostsAsync(string token)
{
try
{
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var r = _httpClient.DefaultRequestHeaders.Authorization.ToString();
_logger.LogInformation($"Authorization: {r}");
var c = _httpClient.BaseAddress.ToString();
_logger.LogInformation($"BaseAddress: {c}");
var response = await _httpClient.GetAsync("Post");
response.EnsureSuccessStatusCode(); // Throw exception if not success
var content = await response.Content.ReadAsStringAsync();
_logger.LogInformation(content);
return JsonConvert.DeserializeObject<Post[]>(content);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
{
var r = _httpClient.DefaultRequestHeaders.Authorization.ToString();
_logger.LogInformation($"Authorization: {r}");
// Handle 401 Unauthorized exception
// Redirect to login page or display a message asking the user to login again
// throw; // Rethrow the exception if you want to handle it further up the call stack
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
_logger.LogError(ex.StatusCode.ToString());
return null; // Return null if an exception occurs
}
catch (Exception ex)
{
// Handle other exceptions
// throw;
var c = _httpClient.BaseAddress.ToString();
_logger.LogInformation($"BaseAddress: {c}");
_logger.LogError(ex.Message);
return null; // Return null if an exception occurs
}
}`
Docker-Compose
`version: “3”
services:
api:
build:
context: .
dockerfile: Stackoverflow.API/DockerFile
image: deboraj/stackoverflow.api
env_file:
– Stackoverflow.API/api.env
volumes:
– stackoverflow-api-log:/app/Logs
ports:
– “6969:80”
entrypoint: [“dotnet”, “Stackoverflow.API.dll”]
web:
build:
context: .
dockerfile: Stackoverflow.Web/DockerFile
image: deboraj/stackoverflow.web
env_file:
- Stackoverflow.Web/web.env
volumes:
- stackoverflow-web-log:/app/Logs
ports:
- "8080:80"
environment:
- API_URL=http://localhost:6969/v3/
entrypoint: ["dotnet", "Stackoverflow.Web.dll"]
volumes:
stackoverflow-api-log:
external: true
stackoverflow-web-log:
external: true
`
when I run the Docker Compose file my API and Web App both should be works, my web app is Dependable on API to get Value.
DEBORAJ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.