如何从外网访问.NET Core 上的WEB API?

How to access WEB API on .NET Core from the outside network?

我想从外面访问我的API?

在本地机器上,我像这样访问我的 API:

https://localhost:44377/api/stations 

例如我的 IP 地址是:186.143.119.43

需要改什么才能外网看到?

这是我的 launchSettings.json 文件:

    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

如何从外部网络访问这个API?

如果出于测试目的考虑使用 ngrok.com

之类的服务

您需要在 rooter Idk 中配置您的端口和 IP 如何执行此操作,但我很早就为我的一款游戏的服务器执行此操作,或者您可以使用 NGROK(我将其用于临时服务器)

Kestral 网络服务器的默认绑定只绑定到 localhost,不允许 public 访问。但是,您可以通过从命令行发送自定义 URL 值来覆盖此设置:

dotnet run --urls http://0.0.0.0:8080

您也可以直接在 Program.cs 文件中配置自定义 URL 值:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                .UseUrls("http://0.0.0.0:8080")
                .UseStartup<Startup>();
            });
 } 

p.s。仅当您的防火墙允许访问配置的 TCP 端口 (8080) 时,上述方法才有效。