Raspberry Pi で .Net Core の Web アプリケーションを作成


プロジェクトの作成

mkdir Web01
cd Web01
dotnet new web
$ mkdir Web01
$ cd Web01
$ dotnet new web
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /home/uchida/tmp/Web01/Web01.csproj...
  /home/uchida/tmp/Web01/Web01.csproj の復元が 424.71 ms で完了しました。

Restore succeeded.

次のようなファイルが作成されます。

$ tree
.
├── Program.cs
├── Properties
│   └── launchSettings.json
├── Startup.cs
├── Web01.csproj
├── appsettings.Development.json
├── appsettings.json
└── obj
    ├── Web01.csproj.nuget.cache
    ├── Web01.csproj.nuget.dgspec.json
    ├── Web01.csproj.nuget.g.props
    ├── Web01.csproj.nuget.g.targets
    └── project.assets.json

2 directories, 11 files

次の2つのファイルを修正します。

1) localhost 以外からもアクセスできるようにします。

appsettings.Development.json
{
        "urls": "http://*:5000;https://*:5001",
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

2) html ファイルを送るようにします。

Startup.cs
(省略)
endpoints.MapGet("/", async context =>
                {
                        String ssx = "<!DOCTYPE html>";
                        ssx += "<html lang='ja'>";
                        ssx += "<body>";
                        ssx += "Good Morning!<p />";
                        ssx += "<hr />";
                        ssx += "Dec/29/2019<p />";
                        ssx += "</body>";
                        ssx += "</html>";
                    await context.Response.WriteAsync(ssx);
                });
(省略)

コンパイルと実行

$ dotnet run
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://[::]:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/uchida/tmp/Web01

ブラウザーで http://host:5000/ にアクセス