C# 在Docker Compose中使用REST调用访问其他服务
我想我有一个简单的问题,还没有在网上找到解决办法。我有一个项目,其中包含多个解决方案。我已将它们全部放入一个docker撰写文件。每个服务都有自己的端口:http://localhost:8081, http://localhost:8082 等等 我在港口有服务http://localhost:8081 港口B服务http://localhost:8082. 我尝试使用HttpClient从服务A调用服务B中的端点。进行Rest调用的默认方式。我打电话http://localhost:8081/ServiceA/testcall. 我试图调用一个外部API:,这是可行的。但当我尝试调用自己的端点时,会出现以下错误: 内部服务器错误500 我调试了它,但没有得到更详细的消息 我试过:C# 在Docker Compose中使用REST调用访问其他服务,c#,asp.net,docker,docker-compose,httpclient,C#,Asp.net,Docker,Docker Compose,Httpclient,我想我有一个简单的问题,还没有在网上找到解决办法。我有一个项目,其中包含多个解决方案。我已将它们全部放入一个docker撰写文件。每个服务都有自己的端口:http://localhost:8081, http://localhost:8082 等等 我在港口有服务http://localhost:8081 港口B服务http://localhost:8082. 我尝试使用HttpClient从服务A调用服务B中的端点。进行Rest调用的默认方式。我打电话http://localhost:8081
namespace A_service.Controllers
{
[Route("[controller]")]
[ApiController]
public class ServiceAController : ControllerBase
{
private readonly IServiceARepository _serviceARepository;
public ServiceAController(IServiceARepository serviceARepository)
{
_serviceARepository= serviceARepository;
}
[HttpGet]
public async Task<IActionResult> JustASimpleGetCall()
{
// This call works fine
return("Hello World");
}
[HttpGet("testcall")]
public async Task<IActionResult> GetSomethingFromOtherService()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://service-b:8080/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("ServiceB/simplefunction");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
}
return Ok("Succesful");
}
namespace B_service.Controllers
{
[Route("[controller]")]
[ApiController]
public class ServiceBController : ControllerBase
{
private readonly IServiceBRepository _serviceBRepository;
public ServiceBController(IServiceBRepository serviceBRepository)
{
_serviceBRepository= serviceBRepository;
}
[HttpGet("simplefunction")]
public IActionResult ServiceBFunction()
{
// To simplify, we just return a
// Declaration of the array
string[] str1;
// Initialization of array
str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };
return Ok(str1);
}
版本:“3.0”
服务:
服务A:
建造:
上下文:。
dockerfile:serviceA/dockerfile
端口:
- "8081:80"
服务B:
建造:
上下文:。
dockerfile:serviceB/dockerfile
环境:
-服务器URL=http://service-b:8080
端口:
- "8082:80"
如果您想从serviceA访问serviceB,url是http://serviceB:(应用程序端口)您的应用程序似乎在端口80上运行(至少这是docker compose.yml中编写的)。如果您可以从计算机(如localhost:8082)访问serviceB,则意味着端口配置为80。
如果应用程序中的端口配置为8080,则意味着您需要写入的端口是8080。但它如何知道我指的是serviceB的8080端口,而不是serviceA的8080端口?因为这两项服务都是指:80?首先,我需要问一下它是否有助于解决问题。其次,认为每个服务本身就是一个docker容器,docker compose为每个服务提供了一个DNS,它是服务的名称,这就是我说的原因。此外,如果您希望从操作系统而不是从服务a访问服务B,您将配置为转到8082而不是8080,因此您希望向localhost:8082发送请求。是的,它可以工作。谢谢我一开始不知道你的意思。酷,你能选择我的答案作为正确答案吗?是的,我把它标记为正确!