Asp.Net Core Web API 应用程序:如何更改监听地址?

Posted

技术标签:

【中文标题】Asp.Net Core Web API 应用程序:如何更改监听地址?【英文标题】:Asp.Net Core Web API app: how to change listening address? 【发布时间】:2018-10-10 08:34:35 【问题描述】:

我编写了简单的 Asp.Net Core WebAPI 2.0 应用程序,它可以在我的本地机器上运行。 但我想将它部署到服务器。 所以,我做到了。

我的系统:

Ubuntu 16.04.
Asp.Net WebAPI 2.0 (and dotnet version 2.1.105)

但是,当应用程序启动时,它会写:

Now listening on:http://localhost:53115

当我尝试从中获取值时:

  http://id_address:53115/api/values

我无法得到回应。 在邮递员中:

 Could not get any response
 There was an error connecting to 
 http://id_address:53115/api/values.
 Why this might have happened:
 The server couldn't send a response:
 Ensure that the backend is working properly
 Self-signed SSL certificates are being blocked:
 Fix this by turning off 'SSL certificate verification' in Settings > General
 Proxy configured incorrectly
 Ensure that proxy is configured correctly in Settings > Proxy
 Request timeout:
 Change request timeout in Settings > General

我该怎么办?你能告诉我如何解决这个问题吗?

我不知道从哪里开始寻找。

谢谢!

【问题讨论】:

如果您使用 Kestrel 托管它,那么默认端口是 5000 @SimplyGed,我尝试 5000,但它是一样的 【参考方案1】:

我使用的是 .NETCore 2.1 prev,所以我无法自己测试它,但如果我相信 https://www.billbogaiv.com/posts/setting-aspnet-host-address-in-net-core-2,添加 .UseUrls(urls: "http://*:5000") 可能会指示 Kestrel 侦听端口 5000,而不仅仅是在 localhost ,所以它应该也可以在远程服务器上工作。

其他可能的解决方案,UseKestrel(..) https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.1&tabs=aspnetcore2x 使用 IPAddress.Any 而不是 Loopback

【讨论】:

【参考方案2】:

这个由Server urls主机配置配置

指示服务器应侦听请求的端口和协议的 IP 地址或主机地址。:urls类型:字符串默认:http://localhost:5000设置使用:UseUrls 环境变量:ASPNETCORE_URLS

设置为服务器应响应的 URL 前缀的分号分隔 (;) 列表。


也可以使用命令行参数设置 URL。例如:

dotnet 运行 --urls=http://0.0.0.0:5001

但这不适用于旧版本的 ASP.NET Core (depends on whether this fix applied to used version or not)。

基于您始终可以通过.UseConfiguration 方法直接设置主机设置这一事实的旧版本解决方法:

var config = new ConfigurationBuilder().AddCommandLine(args).Build();

return WebHost.CreateDefaultBuilder(args)
        .UseConfiguration(config)

注意,同样的想法可以用于从任何其他配置源读取设置值,例如configuration file。

【讨论】:

我在--urls 选项上尝试了各种变体,但我什么都做不了【参考方案3】:

试试下面的,它对我有用。

设置 ASPNETCORE_SERVER.URLS=http://0.0.0.0:5000/

【讨论】:

以上是关于Asp.Net Core Web API 应用程序:如何更改监听地址?的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core Web API

Asp.net core 3.1 保护 API 和 Web 应用程序

ASP.NET Core Web API 身份验证

Asp.Net Core Web API 应用程序:如何更改监听地址?

Xamarin Mobile 使用的 ASP.Net Core Web API

处理 ASP.NET Core Web API 对象属性绑定