在本地网络 Raspberry Pi 3B+ 上托管 ASP.NET

Hosting ASP.NET on Raspberry Pi 3B+ for local network

我正在尝试在我的 Raspberri Pi 3B + 上托管一个 API (ASP.NET)。我想从我的 laptop/phone/pc 等

访问这个 API swagger 页面

到目前为止我尝试过的: 在我的 RPi 上使用 dotnet 安装、编译、构建和 运行 网络应用程序。

RPi 上的

运行ning dotnet --info 为我们提供了以下信息:

.NET SDK (reflecting any global.json):
 Version:   5.0.405
 Commit:    63325e1c7d

Runtime Environment:
 OS Name:     raspbian
 OS Version:  11
 OS Platform: Linux
 RID:         linux-arm
 Base Path:   /usr/share/dotnet/sdk/5.0.405/

Host (useful for support):
  Version: 5.0.14
  Commit:  d5b56c6327

.NET SDKs installed:
  5.0.405 [/usr/share/dotnet/sdk]

.NET runtimes installed:
  Microsoft.AspNetCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 5.0.14 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

当我运行程序(文件路径~/first-rpi-api/bin/Release/net5.0/publish/first-rpi-api

我得到以下信息:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/pi/first-rpi-api/bin/Release/net5.0/publish

swagger UI 的默认 URL 将是:https://localhost:44335/swagger/index.html 但是,当我尝试从 URL 上的 PC 访问 API 时:https://RPi_IP:5000/swagger/index.html

我得到ERR_CONNECTION_REFUSED

我该如何解决这个问题?我错过了什么吗?我该如何解决这个问题?

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001

监听 localhost 意味着它只监听来自同一台机器的网络连接(在您的例子中是 Raspberry Pi)。如果想让它监听机器外的网络连接,需要监听0.0.0.0.

在没有看到您设置网络连接的代码的情况下,很难确定可以很好地集成的修复程序会是什么样子,但请在 运行 您的程序之前尝试这样做:

export ASPNETCORE_URLS="http://*:5000;https://*:5001"

这将使您的应用程序允许来自任何地方的连接。

使用之前的答案(参考omajid的答案)只能为我们提供一个临时的解决方案。

每当您重新启动 Raspberry Pi 时,您都需要执行命令

export ASPNETCORE_URLS="http://*:5000;https://*:5001"

一次又一次。

为了防止这种情况,我建议使用 IHostBuilder.UseUrls("URLS") 方法。

在您的情况下,您需要编辑 Program.cs 并在 CreateHostBuilder 方法中添加以下行。

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();

                    //THIS LINE
                    webBuilder.UseUrls("http://*:5000;https://*:5001"); 
                });

这将自动确保您可以从您喜欢的任何设备访问 API。

您可以在 article 中阅读更多相关信息: