У меня есть решение .NET 7 со шлюзом API: один API — это шлюз, а два других — WebAPI1 и WebAPI2. Эти три APIS представляют собой закрепленные проекты.
У меня есть еще один контейнер — закрепленная база данных SQL Server.
Операционная система моего компьютера — Windows 11.
Несмотря на все мои усилия, я не могу подключить свои веб-API к своей базе данных.
Вот какую ошибку я получаю:
< blockquote>
Microsoft.Data.SqlClient.SqlException: «При установлении соединения с SQL Server произошла ошибка, связанная с сетью или конкретным экземпляром. Сервер не найден или не был доступен. Убедитесь, что имя экземпляра правильное и что SQL Server настроен на разрешение удаленных подключений. (поставщик: сетевые интерфейсы SQL, ошибка: 44 — не удалось составить имя участника-службы (SPN) для встроенной проверки подлинности Windows. Возможные причины: серверы неправильно указаны для вызовов API подключения, сбой поиска системы доменных имен (DNS) или нехватка памяти. )'
Ошибка происходит в моем проекте WebAPI1, в Program.cs, где вызывается метод миграции:
Код: Выделить всё
var applicationConnectionString = builder.Configuration.GetConnectionString("ApplicationConnection");
builder.Services.AddDatabaseContext(applicationConnectionString!);
builder.Services.AddIdentityContext(applicationConnectionString!);
builder.Services.AddDbContext(options => options.UseSqlServer(applicationConnectionString));
builder.Services.AddDbContext(options => options.UseSqlServer(applicationConnectionString));
using (var serviceScope = app.Services.GetService()!.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetRequiredService();
dbContext.Database.Migrate(); // The error is happening here
var identityContext = serviceScope.ServiceProvider.GetRequiredService();
identityContext.Database.Migrate();
}
Строка подключения:
Код: Выделить всё
"ApplicationConnection": "Data Source=127.0.0.1,8001;Initial Catalog=MyDatabase;User Id={username}; Password={password};Trusted_Connection=true;TrustServerCertificate=True"
Код: Выделить всё
"ApplicationConnection": "Server=127.0.0.1,8001;Database=MyDatabase;User Id={username}; Password={password};Trusted_Connection=true;TrustServerCertificate=True"
Код: Выделить всё
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
EntityOne.Configure(modelBuilder);
EntityTwo.Configure(modelBuilder);
EntityThree.Configure(modelBuilder);
EntityFour.Configure(modelBuilder);
}
public DbSet EntityOne { get; set; }
public DbSet EntityTwo { get; set; }
public DbSet EntityThree { get; set; }
public DbSet EntityFour { get; set; }
public async Task SaveChangesAsync()
{
return await base.SaveChangesAsync();
}
}
Код: Выделить всё
WebApi1Код: Выделить всё
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["WebAPIs.WebApi1/WebAPIs.WebApi1.csproj", "WebApi1.Calendar/"]
COPY ["Core/Core.csproj", "Core/"]
COPY ["Infrastructure/Infrastructure.csproj", "Infrastructure/"]
COPY ["Infrastructure/Infrastructure.csproj", "Infrastructure/"]
RUN dotnet restore "./WebAPIs.WebApi1/WebAPIs.WebApi1.csproj"
COPY . .
WORKDIR "/src/WebAPIs.WebApi1"
RUN dotnet build "./WebAPIs.WebApi1.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./WebAPIs.WebApi1.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=true
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebAPIs.WebApi1.dll"]
Код: Выделить всё
docker-compose.yml:
version: '3.4'
services:
database:
container_name: database
image: mcr.microsoft.com/mssql/server:2022-preview-ubuntu-22.04
environment:
- ACCEPT_EULA=Y
- SA_DB_NAME= MyDatabase
- SA_USER={username}
- SA_PASSWORD={password}
# volumes:
# - sqlserver_data:/var/opt/mssql
ports:
- 127.0.0.1:8001:1433
webapis.gateway:
container_name: webapis.gateway
image: ${DOCKER_REGISTRY-}gateway
build:
context: .
dockerfile: WebAPIs.Gateway/Dockerfile
ports:
- 127.0.0.1:5020:80
- 127.0.0.1:7055:443
depends_on:
- database
webapis.webapi1:
image: ${DOCKER_REGISTRY-}webapisapi1
build:
context: .
dockerfile: WebAPIs. WebApi1/Dockerfile
ports:
- 127.0.0.1:5234:80
- 127.0.0.1:7207:443
depends_on:
- database
webapis.webapi2:
container_name: webapis. webapi2
image: ${DOCKER_REGISTRY-} webapisapi2
build:
context: .
dockerfile: WebAPIs.WebApi2/Dockerfile
ports:
- 127.0.0.1:5013:80
- 127.0.0.1:7090:443
depends_on:
- database
Код: Выделить всё
docker-compose.override.yml:
version: '3.4'
services:
webapis.gateway:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_HTTP_PORT=80
- ASPNETCORE_HTTPS_PORT=443
ports:
- 127.0.0.1:5020:80
- 127.0.0.1:7055:443
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
webapis.webapis1:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:443;http://+:80
ports:
- 127.0.0.1:5234:80
- 127.0.0.1:7207:443
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
webapis.webapis2:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:443;http://+:80
ports:
- 127.0.0.1:5013:80
- 127.0.0.1:7090:443
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
- My containers are running in Docker Desktop.
- I can access my database manually, through SSMS.
- SQL Server remote connection to my server is allowed.
- I looked at my firewall, SQL Server and Docker are allowed.
Источник: https://stackoverflow.com/questions/781 ... r-database
Мобильная версия