我有一个.net核心http服务器,该服务器可在本地Windows和Linux计算机上工作。当我尝试在AWS上部署它时,我不能让它监听其公共IP地址。这样做给了我一个例外:
未处理的异常:System.Net.HttpListenerException:无法分配请求的地址
如果我尝试监听其私有IP,则程序将无例外运行,因此我无法将任何http请求发送到其公共IP地址。
我确认安全组设置和ufw状态表明在两种情况下都允许使用端口80。是什么原因造成的?
答案 0 :(得分:0)
设置服务时,您可以保留其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();
}