为什么我可以从 .Net Core 3.1 Web 应用程序在本地运行外部 HTTP 调用,但在发布到 Azure 网站时却不能?

问题描述 投票:0回答:1

我有一个发布到 Azure 网站的 .Net Core 3.1 服务器。作为该服务器的一部分,它有一个 API 端点,我需要用另一个应用程序来调用它。此端点的控制器做了几件事,但最关键的是,它使用以下方法调用另一个外部 API 端点。HttpClient.

我不知道 认为 问题出在任何代码上,但作为参考,这是服务器到外部API的HTTP请求的样子。

try
{
    string endpoint = baseAdress + cpe;
    string responseBody = await client.GetStringAsync(endpoint);

    // ... It fails at the line above, the rest of this just parses the response body
}
catch (HttpRequestException e)
{
    Console.WriteLine("\nException Caught!");
    Console.WriteLine("Message :{0} ", e.Message);
    // "Response status code does not indicate success: 502 (Bad Gateway)."
}

当我在本地运行这台服务器 并将我的客户端应用程序设置为在localhost调用服务器端点时 一切都很顺畅 控制器运行,调用这个外部API,获取结果,然后做一些解析,并返回一个响应给我的客户端应用程序。

当我将服务器发布到Azure,并让客户端将其API调用指向那里时,没有问题。但是,服务器试图调用外部 API 的结果是一个 502 错误。

Azure是否阻止服务器调用外部端点?还是我遗漏了一些需要更改的设置?我以前从来没有使用过Azure网站,所以这对我来说都是非常新的领域,如果我犯了一些愚蠢的假设错误,请原谅。我所看到的唯一其他人发布的这些问题都有超时的问题,但是当我在本地运行这个问题时,一般都是在30秒内完成,所以我不相信这是这里的问题。

c# azure asp.net-core azure-web-sites dotnet-httpclient
1个回答
0
投票

由于你要在不同的域上调用 API,请确保 CORS 在您的网络应用上启用。

az resource update --name samsapp--resource-group myResourceGroup --namespace Microsoft.Web --resource-type config --parent sites/<app_name> --set properties.cors.allowedOrigins="['http://api.com']" --api-version 2015-06-01
© www.soinside.com 2019 - 2024. All rights reserved.