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

Ben*_*son 5 .net c# .net-core

我想从外部访问我的 API 吗?

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

https://localhost:44377/api/stations 
Run Code Online (Sandbox Code Playgroud)

例如我的 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"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何从外网访问该API?

cod*_*.sj 10

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

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

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

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>();
            });
 } 
Run Code Online (Sandbox Code Playgroud)

ps 上述方法仅在您的防火墙允许访问配置的 TCP 端口(8080)时才有效。