远程连接到.net核心自托管的web api

Cal*_*nus 24 c# self-hosting asp.net-web-api .net-core

我有一个简单的.net核心web api,只有一个动作:

[Route("[action]")]
public class APIController : Controller
{
    // GET api/values
    [HttpGet]
    public string Ping()
    {
        return DateTime.Now.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我通过dotnet运行运行,我得到

Hosting environment: Production
Content root path: C:\Users\xxx\Documents\Visual Studio 2015\Projects\SelfHostTest\src\SelfHostTest
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Run Code Online (Sandbox Code Playgroud)

转到浏览器并输入http:// localhost:5000/ping会导致成功返回当前时间.但是,转到远程计算机(相同的LAN)并尝试通过http:// odin:5000/ping访问服务会导致404错误.(Odin是通过dotnet运行在控制台中运行web api的机器的名称).

服务器(和客户端!)防火墙都已关闭.我可以成功地ping"odin".

任何想法我在这里缺少什么简单的步骤.我在家里和工作中尝试过这种方法并没有成功.

Fea*_*ron 42

我的猜测是问题不在你的控制器中,而是在program.cs中.您需要修改WebHost的构造

var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://localhost:5000", "http://odin:5000", "http://192.168.1.2:5000")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
Run Code Online (Sandbox Code Playgroud)

除非你添加UseUrls行,否则Kestrel不会在localhost之外监听.这是有道理的,因为在正常情况下,Kestrel将坐在IIS或NGNIX等反向代理之后,不需要绑定到外部URL.

  • 另外,您可以使用`.UseUrls("http://*:5000")`来接受来自端口`5000`的任何传入请求! (8认同)
  • 或者您可以使用特殊的ASPNETCORE_URLS环境变量.不过,我不想直接用Kestrel在制作中听.最好让它落后于其他东西. (3认同)
  • 谢谢-这有效!猜猜这种配置确实需要放在某种配置文件中吗? (2认同)

小智 34

The best way is to adjust the launchSettings.json, which is located inside the Properties folder.

Change

"applicationUrl": "https://localhost:5001"
Run Code Online (Sandbox Code Playgroud)

to

"applicationUrl": "https://0.0.0.0:5001"
Run Code Online (Sandbox Code Playgroud)

This allows the Kestrel Web Server to listen for traffic from all Network Interfaces.

  • asp.net core 3.1中有两个applicationUrl部分,我在哪里添加这部分? (2认同)

Ale*_*man 9

您只需执行以下操作即可创建您的WebHost,这将允许远程连接到kestrel。

var host = WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://0.0.0.0:80")
                .UseStartup<Startup>()
                .Build();
Run Code Online (Sandbox Code Playgroud)

使用以下代码后,我仍然无法远程访问我的API,我不得不在Windows控制面板(控制面板\网络和Internet \网络连接)中禁用Docker创建的网络适配器。


小智 7

对于我们来说,它也有效(我不知道这是否是 core 3.1 的新功能):

 public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel();
                webBuilder.UseIIS();
                webBuilder.UseUrls("http://*:8080");
                webBuilder.UseStartup<Startup>();
            });
Run Code Online (Sandbox Code Playgroud)


Men*_*ndy 5

以我的情况(.NET Core 2.1),我必须修改Properties/launchSettings.json文件。

将设置applicationUrl为允许的网址列表,用分号分隔,如下所示

"applicationUrl": "https://localhost:5001;http://odin:5000"
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人。