.net - 无法在 AWS 上的公共 ip 端口 80 上侦听
问题描述
我有一个在本地 Windows 和 linux 机器上工作的 .net 核心 http 服务器。当我尝试在 AWS 上部署它时,我不能让它监听它的公共 IP 地址。这样做给了我一个例外:
未处理的异常:System.Net.HttpListenerException:无法分配请求的地址
如果我尝试监听它的私有 ip,程序毫无例外地运行,我无法向它的公共 ip 地址发送任何 http 请求。
我确认安全组设置和 ufw 状态显示在这两种情况下都允许使用端口 80。问题的原因可能是什么?
解决方案
设置服务时,您可以留下它的 URL/IP,以便它可以在您加载它的任何地方进行监听。下面的代码示例演示了这一点,以及如何注入 URL 或端口的示例。它提供了动态加载服务的灵活性(参数通过方法的参数注入)。
public static void Main(string[] args)
{
// using NuGet package: Microsoft.Extensions.Configuration.CommandLine
// Build the config from the command line arguments
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
// a default port
int port = 5011;
// receive the port as an input
port = config.GetValue<int>("port", port);
// receive the whole URL as an input
string url = config.GetValue<string>("url");
// the URL can be *, not necessarily localhost.
//It allows flexibility in deploying it in any platform/host.
url = String.IsNullOrEmpty(url) ? $"http://*:{port}/" : url;
// initialize the applicative logger
ILogger logger = InitializeLogger(config);
// initialize the web host
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.ConfigureServices(log=>
log.AddSingleton<ILogger>(logger)) // set the applicative logger
.ConfigureServices(collection=>
collection.AddSingleton<IConfiguration>(config)) // send the command line arguments to Startup instance
.UseStartup<Startup>()
.UseUrls(url) // set the URL that has been composed above
.Build();
Console.WriteLine($"Host is up and running in URL: {url}");
host.Run();
}
推荐阅读
- react-native - React-Native - 无法使用 GradleScopeCompileServices.configure() 配置服务
- data-conversion - 如何将线性刻度转换为对数刻度
- python - 为什么我的表单验证在 django 中不起作用
- qt-creator - QT:“这个文件不是任何项目的一部分”
- google-cloud-platform - 使用 dtmf 响应从对话流中响应(播放数字)
- c - 我想确定我的代码中最常出现的两个字母组合
- python - Python argparse 为空
- sql - 有没有办法结合2个查询?
- javascript - 如何在 Firebase 中实现分布式倒数计时器
- google-play-console - 即使我更改了软件包名称,Google 控制台仍然拒绝我的 aab 文件