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

问题描述

我有一个发布到 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#azureasp.net-coreazure-web-app-servicedotnet-httpclient

解决方案


由于您在不同域上调用 API,因此请确保在您的 Web 应用上启用了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

推荐阅读