You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Aspire服务发现无法找到PostgreSQL服务器,求排查错误

问题描述

使用.NET Aspire配置PostgreSQL和Web项目时,服务发现无法找到PostgreSQL服务器,抛出错误:

System.Net.Sockets.SocketException: 'No such host is known.'

AppHost配置代码:

var postgres = builder
    .AddPostgres("Postgres", port: 5432)
    .WithImageTag("latest")
    .WithContainerName("MyDatabase-PostgresDb-Aspire")
    .WithEnvironment("POSTGRES_USER", "postgres")
    .WithEnvironment("POSTGRES_PASSWORD", "postgrespassword")
    .WithEnvironment("POSTGRES_DB", "MyDatabase")
    .WithEnvironment("POSTGRES_HOST_AUTH_METHOD", "trust")
    .WithDataBindMount(source: "F:\\DockerVolumes\\Postgres\\Data", isReadOnly: false)
    .WithLifetime(ContainerLifetime.Persistent)
    .AddDatabase("MyDatabase");


var web = builder.AddProject<ArshidWeb>(nameof(ArshidWeb))
    .WithExternalHttpEndpoints()
    .WithScalar().WithSwagger().WithOpenApi()
    .WaitFor(postgres)
    .WithReference(postgres);

连接字符串配置:

"ConnectionStrings": {
    "PostgresConnection":"Host=Postgres;Port=5432;Database=MyDatabase;Username=postgres;Password=postgrespassword;"
}

注:使用docker-compose.yml和Dockerfile时该配置运行正常,但.NET Aspire环境下出错。

解决方案

问题出在硬编码连接字符串的主机名,.NET Aspire的服务发现机制依赖内置的配置传递和服务名称解析,而非直接使用容器名或手动指定的主机名。以下是修正步骤:

  1. 移除Web项目中硬编码的连接字符串
    删除appsettings.json里的PostgresConnection配置项,让Aspire自动注入正确的连接字符串。

  2. 在Web项目中绑定Aspire数据库配置
    确保Web项目已安装Aspire.Npgsql.EntityFrameworkCore.PostgreSQL包,然后在Program.cs中添加代码,通过Aspire的服务引用获取连接字符串:

    builder.AddNpgsqlDbContext<YourDbContext>("MyDatabase");
    

    这里的"MyDatabase"必须和AppHost中AddDatabase("MyDatabase")的名称完全一致,Aspire会自动将Postgres服务的连接字符串注入到DbContext中。

  3. 验证服务引用关系
    AppHost中web.WithReference(postgres)已建立Web项目与Postgres服务的依赖关系,Aspire会自动处理服务发现和连接字符串传递,无需手动指定Host=Postgres。

  4. 可选:手动获取连接字符串
    如果不使用DbContext,也可以通过IConfiguration获取Aspire注入的连接字符串:

    var connectionString = builder.Configuration.GetConnectionString("MyDatabase");
    
原因说明

在.NET Aspire环境中,服务运行在Aspire创建的专用网络中,服务名称的解析由Aspire的服务发现组件处理。手动硬编码Host=Postgres无法被Aspire的服务发现机制正确解析,而通过AddDatabase和WithReference的组合,Aspire会自动生成包含正确服务地址的连接字符串并注入到Web项目中。

内容的提问来源于stack exchange,提问作者Arash.Zandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 02:52:21