.NET6 以降の ASP.NET Core アプリケーションでIWebHostEnvironment オブジェクトを利用するコードを紹介します。
.NET5以前のASP.NET Core アプリケーションと .NET6以降のASP.NET Core アプリケーションでは、
アプリケーション初期化部分のひな型コードが大きく変化し、アクセス方法が異なるものがあります。
この記事では、IWebHostEnvironment オブジェクトを.NET6以降のASP.NET Coreアプリケーションで利用するコードを紹介します。
WebApplicationオブジェクト (app変数) のEnvironment プロパティがIWebHostEnvironment オブジェクトになります。
.NET5 以前のASP.NET Core アプリケーションは以下の記述です。
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>();
});
}
}
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 以降のASP.NET Coreのコードにした場合、次の通りになります。
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()
で呼び出しができます。