1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.NET備忘録

Posted at

環境構築

dotnet --version

7以上推奨

dotnet new webapi -minimal -n TodoApi

出来上がったディレクトリ構造はこんな感じ。よくみるとControllerやViewなどはまだなく、あるのはProgram.cs, Propertiesなどだ。
image.png

しかしProgram.csをよくみると、あら不思議、なんかAPIっぽいのが既に書いてあるではないか。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast =  Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

dotnet new webapi -minimal -n TodoApiコマンドを実行したときに自動生成されたものだと考えられる。Swaggerまであって便利だ。

ここから、いらない部分を剥ぎ取る。
とりあえずTDD的な感じで、最小限のコードまではぎ取り、buildの成功を狙う。

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.Run();

このコードは、.NET 8を使用して最小限のWeb APIを作成するためのものである。以下に各行の解説を示す。

var builder = WebApplication.CreateBuilder(args);

ここでは、WebApplication.CreateBuilderメソッドを使用して新しいWebアプリケーションのビルダーを作成している。argsはプログラムの引数を受け取り、ビルダーに渡す。

var app = builder.Build();

次に、builder.Buildメソッドを使用して、アプリケーションオブジェクトを作成している。このオブジェクトは、Webアプリケーションの設定および中核部分を持つ。

app.Run();

最後に、app.Runメソッドを呼び出して、アプリケーションを実行している。このメソッドは、HTTPサーバーを起動し、リクエストの受け取りと処理を開始する。

以上が最小限のWeb APIを構築するための基本的なコードである。これにより、簡単なWebアプリケーションを迅速に立ち上げることができる。

ビルドする

cd TodoApi
dotnet build

でビルドする。
image.png
ビルド成功。

実行してみる

dotnet run

image.png
もちろんこれ以外はなにも起きない。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?