要解决ASP.NET Core Web API服务无法连接到相同网络上的Docker SQL Server的问题,可以尝试以下解决方法:
version: '3'
services:
webapi:
build:
context: .
dockerfile: Dockerfile
ports:
- 5000:80
depends_on:
- sqlserver
networks:
- mynetwork
sqlserver:
image: mcr.microsoft.com/mssql/server
environment:
SA_PASSWORD: your_password
ACCEPT_EULA: Y
ports:
- 1433:1433
networks:
- mynetwork
networks:
mynetwork:
在上面的示例中,webapi
和sqlserver
容器都添加到名为mynetwork
的网络中。
{
"ConnectionStrings": {
"DefaultConnection": "Server=sqlserver;Database=your_database;User Id=your_username;Password=your_password;"
},
...
}
在上面的示例中,连接字符串中的Server
设置为sqlserver
,这是Docker Compose文件中定义的SQL Server容器的服务名。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
}
在上面的示例中,YourDbContext
是你的数据库上下文类,Configuration.GetConnectionString("DefaultConnection")
获取appsettings.json中的连接字符串。
这些解决方法应该能够帮助你解决ASP.NET Core Web API服务无法连接到相同网络上的Docker SQL Server的问题。记得替换示例代码中的数据库名称、用户名和密码为你自己的信息。