我正在azure上做一个测试项目。我部署了 4 个应用程序服务。全部位于不同地区,全部免费。
部署的应用程序服务之一应该是与所有其他服务通信的网关。
我在本地运行网关的代码,但保留了其他应用程序服务的部署网址,一切正常。
部署网关后,我总是会收到 502 bad gateway 错误。
这里可能出现什么问题?
我的 FastEndpoints 设置如下:
public class GetFlashCardEndpoint : Endpoint<EntityRequest, Response<FlashCardResponse>>
{
public IOptionsMonitor<GatewayOptions> OptionsMonitor { get; set; }
public HttpClientService HttpClientService { get; set; }
public override void Configure()
{
Get("/flash-cards/{Id}");
Summary(s =>
{
s.Summary = "Returns a specific flashcard";
s.Description = "This endpoint retrieves a flashcard by its ID for a specified user ID.";
s.Params["Id"] = "The unique identifier of the flash card";
});
}
public override async Task HandleAsync(EntityRequest request, CancellationToken cancellationToken)
{
var url = $"{OptionsMonitor.CurrentValue.FlashCardsHost}/flash-cards/{request.EntityId}";
await HttpClientService.SendRequestAsync(url, cancellationToken);
}
public async Task<HttpResponseMessage> SendRequestAsync(string url, CancellationToken cancellationToken)
{
var method = new HttpMethod(_context.Request.Method);
var requestMessage = new HttpRequestMessage(method, url);
Log.Information("HttpClientService reached SendRequestAsync.");
AddHeaders(requestMessage);
if (_context.Request.ContentLength > 0 && (method == HttpMethod.Post || method == HttpMethod.Put || method == HttpMethod.Patch || method == HttpMethod.Delete))
{
var requestBody = await _context.Request.GetRawBodyAsync();
requestMessage.Content = new StringContent(requestBody, Encoding.UTF8, _context.Request.ContentType);
}
HttpResponseMessage response = await _httpClient.SendAsync(requestMessage, cancellationToken);
await StreamResponseBackToClient(response, cancellationToken);
return response;
}
private async Task StreamResponseBackToClient(HttpResponseMessage response, CancellationToken cancellationToken)
{
_context.Response.StatusCode = (int)response.StatusCode;
foreach (var header in response.Headers)
{
_context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var contentHeader in response.Content.Headers)
{
_context.Response.Headers[contentHeader.Key] = contentHeader.Value.ToArray();
}
if (response.Content != null)
{
await response.Content.CopyToAsync(_context.Response.Body, cancellationToken);
}
}
我想强调的是,此设置在本地运行时功能齐全。
在已部署的网关应用程序上调用端点后,日志将显示我已成功与其他服务进行通信,但网关将“旋转”更长时间,即使与之通信的服务返回了响应。
我怀疑 502 bad gateway 是由于超时而被抛出的,因为如果您查看端点逻辑,我不会发回响应,而是我的作用域 httclient 服务会直接修改 http 上下文,如 StreamResponseBackToClient 中所示,由于某种原因,我无法理解本地的工作原理,但在云中却不行。
当我发布问题时,我以为我的请求无法到达其他服务,因为它们部署在不同的区域。我被告知情况并非如此,并且不需要任何额外的配置,应用程序应该不会出现通信问题,然后我在检查日志后确认了这一点。
最后我无法找出问题所在,只是转而使用.net Ocelot,结果成功了。