.NET6 以降の ASP.NET Core アプリケーションでIWebHostEnvironment オブジェクトを利用する - ASP.NET Core

.NET6 以降の ASP.NET Core アプリケーションでIWebHostEnvironment オブジェクトを利用するコードを紹介します。

概要

.NET5以前のASP.NET Core アプリケーションと .NET6以降のASP.NET Core アプリケーションでは、 アプリケーション初期化部分のひな型コードが大きく変化し、アクセス方法が異なるものがあります。
この記事では、IWebHostEnvironment オブジェクトを.NET6以降のASP.NET Coreアプリケーションで利用するコードを紹介します。

利用方法

WebApplicationオブジェクト (app変数) のEnvironment プロパティがIWebHostEnvironment オブジェクトになります。

コード

.NET5 以前

.NET5 以前のASP.NET Core アプリケーションは以下の記述です。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace iPentecSampleApp
{
  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.UseStartup<Startup>();
            });
  }
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace iPentecSampleApp
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
              {
            await context.Response.WriteAsync("Hello World!");
          });
      });
    }
  }
}

以下のコードで、IWebHostEnvironment オブジェクトの IsDevelopment() メソッドを呼び出して判定をしています。 この部分を.NET6に移植する際に、IWebHostEnvironment オブジェクトのアクセス先がわからないことがあります。
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

.NET6 以降

上記のコードを .NET6 以降のASP.NET Coreのコードにした場合、次の通りになります。
Program.cs (最上位レベルのステートメント(Top-level statements)を使用しない場合)
namespace iPentecSampleApp
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var builder = WebApplication.CreateBuilder(args);
      var app = builder.Build();

      if (app.Environment.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.MapGet("/", () => "Hello World!");

      app.Run();
    }
  }
}

app変数のEnvironmentプロパティがIWebHostEnvironment であるため、app.Environment.IsDevelopment() で呼び出しができます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-02-13
作成日: 2024-02-11
iPentec all rights reserverd.