c# - 网络 docker 容器上的 HttpClient 请求

标签 c# docker asp.net-core-webapi docker-networking

我是 docker 容器的新手,我遇到了以下问题。我正在开发一个向公开的 api 发出请求的网页。它们都发布在通过网络链接的不同容器上。 这是我的 docker-compose.yml 文件:

version: '2'

services:
  api:
    image: my/api
    networks:
      - api
    ports:
      - "8080:5000"    
    container_name: api  

  web:
    build:
      context: ./DockerWeb      
    networks:
      - api      
    ports:
      - "80:5000"    
    container_name: web

networks:    
  api:
    driver: bridge

我注意到,如果我附加到运行我的网页的容器,我可以使用 ping api

毫无问题地 ping api 容器

当尝试对 api 容器进行任何网络服务调用时,问题就出现了。我正在尝试初始化一个 HttpClient 对象,但是必须将此类对象的 BaseAddress 属性设置为有效的 Uri。

_client = new HttpClient();
_client.BaseAddress = new Uri(config.ApiUrl); //config.ApiUrl = "api"

这会引发以下错误

UriFormatException: Invalid URI: The format of the URI could not be determined.

有没有办法 a) 以不同的方式公开容器名称,或者 b) 在不需要使用 URI 的情况下调用 Web 服务? 我怎样才能做到这一点?

更新

我已经更新了 ApiUrl 以包含值 http:api:8080,但是现在我在执行调用时遇到异常

System.AggregateException: One or more errors occurred. (An error occurred while sending the request.) ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.CurlException: Couldn't connect to server

我还尝试使用 wget 直接从我的 Web 容器调用 api 端点

wget http://api:8080/ 

但是我仍然收到一个错误:

Connecting to api (api)|172.24.0.4|:8080... failed: Connection refused

这可能是 API 配置错误吗?

最佳答案

api 只是主机名。 URI 将为 http://api:8080(如果您设置了 SSL/TLS,则为 https://api:someotherport。)

关于c# - 网络 docker 容器上的 HttpClient 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915782/

相关文章:

c# - ComboBox 和 KeyValuePair 列表无法正常工作

java - Dockerized Spring Boot 微服务无故卡住

docker - 如何在 docker 中以分离模式运行 bash?

c# - ASP.NET Core 6 : Users are logged out after 30 minutes, 需要 6 小时

c# - .NET 在数值计算中的速度

c# - 对 Listview C# 上的项目进行排序

macos - 在 macos Mojave 10.14 上从 docker 容器设置 ssh 隧道

asp.net-core-webapi - 为什么 FromQuery 在我的 ASP.Net Core 1.1 Controller 操作中不起作用

c# - 模拟一个方法返回 true 仍然返回 false

asp.net-core - 如果与 JWT 承载身份验证一起使用,Asp.Net 核心 Web API 防伪验证将失败