Skip to content

ASP.NET Core 8 での Startup.cs の利用方法

.NET Framework の ASP.NET MVC から .NET 8 への移行において、Startup.cs ファイルが自動生成されず混乱するケースがあります。このファイルは .NET 8 でも利用可能ですが、新しいアプローチが推奨されており、設計思想が大きく変化しています。


Startup.cs の位置付け

ASP.NET Core(.NET 8を含む)では:

  1. Startup.cs廃止されたわけではない(従来通り使用可能)
  2. ただし .NET 6 以降、Program.cs に設定を集約するMinimal Hosting Modelがデフォルト
  3. テンプレートで自動生成されないのは新しい設計思想によるもの

⚠️ 移行時の注意
OWIN ベースの Startup.cs とは概念が異なります。ASP.NET Core では組み込みの依存性注入とミドルウェアパイプラインを活用します。


設定方法の2つのアプローチ

✅ アプローチ1: Program.cs に集約(推奨)

.NET 6+ の標準スタイル。全設定を1ファイルで管理します。

cs
var builder = WebApplication.CreateBuilder(args);

// 認証設定(例: OAuth)
builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "MyOAuth";
    })
    .AddOAuth("MyOAuth", options =>
    {
        options.ClientId = builder.Configuration["OAuth:ClientId"];
        options.ClientSecret = builder.Configuration["OAuth:ClientSecret"];
        options.CallbackPath = "/signin-oauth";
    });

// DIコンテナへのサービス登録
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<MyDbContext>();

var app = builder.Build();

// ミドルウェアパイプライン設定
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

主なメリット:

  • ファイル分割が不要なためシンプル
  • 新しいテンプレートの標準形式
  • ミドルウェアの順序が直線的に把握可能

✅ アプローチ2: 従来の Startup.cs の継続利用

大規模プロジェクトなどで関心事を分離したい場合に有効です。

Program.cs:

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>(); // Startupクラスを指定
        });

Startup.cs:

cs
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // サービス登録(OAuth設定含む)
        services.AddAuthentication()
            .AddOAuth("OAuthScheme", options => 
            {
                options.ClientId = Configuration["OAuth:ClientId"];
            });
        
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app)
    {
        // ミドルウェアパイプライン
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.MapControllers();
    }
}

認証設定のベストプラクティス

OAuth 設定の具体的な実装例:

cs
builder.Services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = "OAuth";
    options.DefaultSignInScheme = "Cookies";
})
.AddCookie("Cookies")
.AddOAuth("OAuth", options =>
{
    options.AuthorizationEndpoint = "https://api.example.com/oauth/authorize";
    options.TokenEndpoint = "https://api.example.com/oauth/token";
    options.UserInformationEndpoint = "https://api.example.com/userinfo";
    options.SaveTokens = true;
});

ポイント:

  1. AddAuthentication() で認証スキームを指定
  2. AddOAuth() でプロバイダー固有の設定
  3. シークレット情報は構成システム(appsettings.json など)から取得

移行ガイダンス

シナリオ推奨アプローチ
新規プロジェクトProgram.cs 集約方式
小規模アプリProgram.cs 集約方式
大規模既存アプリの移行既存構造を維持+Startup.cs 利用
OWIN からの移行構成モデルを見直し再実装が必要

💡 判断基準
Program.cs が500行を超える場合、Startup.cs への分割を検討しましょう。関心事の分離(SoC)が効果を発揮します。

重要な考慮点:

  • ミドルウェアの順序がセキュリティに直結(UseAuthentication()UseRouting() の後、UseAuthorization() の前に配置)
  • 環境ごとの設定には ConfigureServices 内で if (env.IsDevelopment()) を利用
  • サードパーティライブラリ(例: UseSerilog())は HostBuilder で設定

.NET 8 では両方式とも完全にサポートされていますが、公式ドキュメントやテンプレートは Program.cs 中心のアプローチを推進しています。プロジェクト規模とチームの習熟度に応じて最適な選択を行いましょう。