WSL2 无法访问 PC localhost Kestrel 服务器中的 Web 应用程序

WSL2 Cannot reach web app in the PC localhost Kestrel server

在我的 PC 本地主机 (Win10) 中。我在 Kestrel 中启动 asp.net 核心 Web 应用程序,端口是 8081。

我想在 wsl2 中使用 curl 命令来测试网络应用程序,我发现了问题。

在我的 PC 中找到以下 url 作品。

curl http://localhost:8081/hello    (working) 
curl http://127.0.0.1:8081/hello    (working) 
curl http://192.168.43.216:8081/hello  (working)
curl http://172.25.208.1:8081/hello  (working)

在 wsl2 中,我使用了 curl 命令但无法正常工作。

curl http://192.168.43.216:8081/hello   (not working)
curl http://172.25.208.1:8081/hello     (not working)

我的电脑localhost网卡

Wifi
IPv4: 192.168.43.216
submask: 255.255.255.0
gatway: 192.168.43.1

vEthernet (WSL)
IPv4: 172.25.208.1
submask: 255.255.240.0
gatway:

这是我的 asp.net 核心网络 api 设置。

launchSettings.json 
"PrometheusCoreTest": {
  "commandName": "Project",
  "launchBrowser": true,  
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  },
  "applicationUrl": "http://0.0.0.0:8081"  
}

Web api 控制器

[ApiController]
public class TestController
{
    [HttpGet("/hello")]
    public string Hello()
    {
        return "hello, world";
    }
}

我用netstat找到8081端口,设置防火墙允许8081端口

C:\WINDOWS\system32>netstat -ano | find "8081"
TCP    0.0.0.0:8081           0.0.0.0:0              LISTENING       22092
TCP    [::1]:2184             [::1]:8081             SYN_SENT        22972

但是wsl2中的结果curl http://192.168.43.216:8081/hello还是不行。

如何通过 wsl2 访问本地主机网络应用程序?我是否缺少某些设置?


好的。终于找到问题了

通过wsl2使用telnet测试端口。 (它不起作用。)

> telnet 192.168.43.216 8081
Trying 192.168.43.216...

我发现visual studio项目防火墙被封锁了。不知道为什么vs项目被封了...

只要停止被封锁的规则,然后再次尝试 telnet 测试端口是否正常。

❯ telnet 192.168.43.216 8081
Trying 192.168.43.216...
Connected to 192.168.43.216.
Escape character is '^]'.

使用 curl 命令也能正常工作。

❯ curl http://192.168.43.216:8081/hello
hello, world%