首页 > 解决方案 > 无法在 AWS 上的公共 ip 端口 80 上侦听

问题描述

我有一个在本地 Windows 和 linux 机器上工作的 .net 核心 http 服务器。当我尝试在 AWS 上部署它时,我不能让它监听它的公共 IP 地址。这样做给了我一个例外:

未处理的异常:System.Net.HttpListenerException:无法分配请求的地址

如果我尝试监听它的私有 ip,程序毫无例外地运行,我无法向它的公共 ip 地址发送任何 http 请求。

我确认安全组设置和 ufw 状态显示在这两种情况下都允许使用端口 80。问题的原因可能是什么?

标签: .netamazon-web-servicesamazon-ec2

解决方案


设置服务时,您可以留下它的 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();
    }

推荐阅读