この記事では、.NET 6 の ASP.NET Core に移行されたコードのサンプルを示します。 .NET 6 の ASP.NET Core では、新しい最小ホスティング モデルが使用されます。 詳細については、「 新しいホスティング モデル」を参照してください。
ミドルウェア
次のコードは、.NET 5 アプリに静的ファイル ミドルウェアを追加します。
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
}
次のコードは、.NET 6 アプリの ASP.NET Core に静的ファイル ミドルウェアを追加します。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles();
app.Run();
WebApplication.CreateBuilder は、事前に構成された既定値を使用して WebApplicationBuilder クラスの新しいインスタンスを初期化します。 詳細については、「ASP.NET Core のミドルウェア」を参照してください
経路選択
次のコードは、.NET 5 アプリにエンドポイントを追加します。
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", () => "Hello World");
});
}
}
.NET 6 では、WebApplicationまたはUseEndpointsを明示的に呼び出すことなく、ルートをUseRoutingに直接追加できます。 次のコードは、.NET 6 アプリの ASP.NET Core にエンドポイントを追加します。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
ルートは、パイプラインの WebApplication で実行されます。
コンテンツ ルート、アプリ名、環境を変更する
.NET 5 の ASP.NET Core
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseEnvironment(Environments.Staging)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseSetting(WebHostDefaults.ApplicationKey,
typeof(Program).Assembly.FullName);
});
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ApplicationName = typeof(Program).Assembly.FullName,
ContentRootPath = Directory.GetCurrentDirectory(),
EnvironmentName = Environments.Staging,
WebRootPath = "customwwwroot"
});
Console.WriteLine($"Application Name: {builder.Environment.ApplicationName}");
Console.WriteLine($"Environment Name: {builder.Environment.EnvironmentName}");
Console.WriteLine($"ContentRoot Path: {builder.Environment.ContentRootPath}");
Console.WriteLine($"WebRootPath: {builder.Environment.WebRootPath}");
var app = builder.Build();
詳細については、「ASP.NET Core の基礎の概要」を参照してください
環境変数またはコマンド ラインを使用したコンテンツ ルート、アプリ名、環境の変更
次の表は、コンテンツ ルート、アプリ名、環境を変更するために使用される環境変数とコマンド ライン引数を示しています。
機能 | 環境変数 | コマンドラインの引数 |
---|---|---|
アプリケーション名 | ASPNETCORE_APPLICATIONNAME | --applicationName |
環境名 | ASPNETCORE_ENVIRONMENT | --環境 |
コンテンツ ルート | ASPNETCORE_CONTENTROOT | コンテンツルート |
構成プロバイダーの追加
.NET 5 の ASP.NET Core
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config =>
{
config.AddIniFile("appsettings.ini");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
詳細については、「ASP.NET Core の構成」の「ファイル構成プロバイダー」を参照してください。
ログ プロバイダーを追加する
.NET 5 の ASP.NET Core
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddJsonConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
// Configure JSON logging to the console.
builder.Logging.AddJsonConsole();
var app = builder.Build();
詳細については、「 .NET Core と ASP.NET Core でのログ記録」を参照してください。
サービスを追加する
.NET 5 の ASP.NET Core
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add the memory cache services
services.AddMemoryCache();
// Add a custom scoped service
services.AddScoped<ITodoRepository, TodoRepository>();
}
}
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
// Add the memory cache services.
builder.Services.AddMemoryCache();
// Add a custom scoped service.
builder.Services.AddScoped<ITodoRepository, TodoRepository>();
var app = builder.Build();
詳細については、「ASP.NET Core での依存関係の挿入」を参照してください。
IHostBuilder または IWebHostBuilder をカスタマイズする
IHostBuilder のカスタマイズ
.NET 5 の ASP.NET Core
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
// Wait 30 seconds for graceful shutdown.
builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
var app = builder.Build();
IWebHostBuilder のカスタマイズ
.NET 5 の ASP.NET Core
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
// Change the HTTP server implementation to be HTTP.sys based.
webBuilder.UseHttpSys()
.UseStartup<Startup>();
});
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
// Change the HTTP server implementation to be HTTP.sys based.
// Windows only.
builder.WebHost.UseHttpSys();
var app = builder.Build();
Web ルートを変更する
既定では、Web ルートは、wwwroot
フォルダーのコンテンツ ルートに対して相対的です。 静的ファイル ミドルウェアは、Web ルートで静的ファイルを探します。 Web ルートは、WebRootPathで WebApplicationOptions プロパティを設定することで変更できます。
.NET 5 の ASP.NET Core
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
// Look for static files in webroot.
webBuilder.UseWebRoot("webroot")
.UseStartup<Startup>();
});
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
// Look for static files in webroot
WebRootPath = "webroot"
});
var app = builder.Build();
カスタムの依存関係の挿入 (DI) コンテナー
次の .NET 5 および .NET 6 サンプルでは 、Autofac を使用しています
.NET 5 の ASP.NET Core
Program クラス
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
スタートアップ
public class Startup
{
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
}
}
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// Register services directly with Autofac here. Don't
// call builder.Populate(), that happens in AutofacServiceProviderFactory.
builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new MyApplicationModule()));
var app = builder.Build();
追加のサービスにアクセスする
Startup.Configure
は、 IServiceCollectionを介して追加されたサービスを挿入できます。
.NET 5 の ASP.NET Core
public class Startup
{
// This method gets called by the runtime. Use this method to add services
// to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IService, Service>();
}
// Anything added to the service collection can be injected into Configure.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IHostApplicationLifetime lifetime,
IService service,
ILogger<Startup> logger)
{
lifetime.ApplicationStarted.Register(() =>
logger.LogInformation(
"The application {Name} started in the injected {Service}",
env.ApplicationName, service));
}
}
.NET 6 の ASP.NET Core
.NET 6 の ASP.NET Core の場合:
- WebApplicationでは、最上位レベルのプロパティとして使用できる一般的なサービスがいくつかあります。
-
IServiceProvider
を使用して、から追加のサービスを手動で解決する必要があります。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IService, Service>();
var app = builder.Build();
IService service = app.Services.GetRequiredService<IService>();
ILogger logger = app.Logger;
IHostApplicationLifetime lifetime = app.Lifetime;
IWebHostEnvironment env = app.Environment;
lifetime.ApplicationStarted.Register(() =>
logger.LogInformation(
$"The application {env.ApplicationName} started" +
$" with injected {service}"));
WebApplicationFactory または TestServer を使用してテストする
.NET 5 の ASP.NET Core
次のサンプルでは、テスト プロジェクトでは TestServer
と WebApplicationFactory<TEntryPoint>を使用しています。 これらは、明示的な参照を必要とする個別のパッケージとして出荷されます。
WebApplicationFactory
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="{Version}" />
</ItemGroup>
テストサーバー
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="{Version}" />
</ItemGroup>
.NET 5 コード内の ASP.NET Core
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHelloService, HelloService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHelloService helloService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync(helloService.HelloMessage);
});
});
}
}
TestServer を使用する
[Fact]
public async Task HelloWorld()
{
using var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder =>
{
// Use the test server and point to the application's startup
builder.UseTestServer()
.UseStartup<WebApplication1.Startup>();
})
.ConfigureServices(services =>
{
// Replace the service
services.AddSingleton<IHelloService, MockHelloService>();
})
.Build();
await host.StartAsync();
var client = host.GetTestClient();
var response = await client.GetStringAsync("/");
Assert.Equal("Test Hello", response);
}
class MockHelloService : IHelloService
{
public string HelloMessage => "Test Hello";
}
WebApplicationFactory を使用する
[Fact]
public async Task HelloWorld()
{
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IHelloService, MockHelloService>();
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/");
Assert.Equal("Test Hello", response);
}
class MockHelloService : IHelloService
{
public string HelloMessage => "Test Hello";
}
.NET 6 の ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IHelloService, HelloService>();
var app = builder.Build();
var helloService = app.Services.GetRequiredService<IHelloService>();
app.MapGet("/", async context =>
{
await context.Response.WriteAsync(helloService.HelloMessage);
});
app.Run();
プロジェクト ファイル (.csproj)
プロジェクト ファイルには、次のいずれかを含めることができます。
<ItemGroup>
<InternalsVisibleTo Include="MyTestProject" />
</ItemGroup>
又は
[assembly: InternalsVisibleTo("MyTestProject")]
別の解決策は、 Program
クラスをパブリックにすることです。
Program
は、プロジェクトまたはでpublic partial Program
クラスを定義することで、Program.cs
でパブリックにすることができます。
var builder = WebApplication.CreateBuilder(args);
// ... Configure services, routes, etc.
app.Run();
public partial class Program { }
[Fact]
public async Task HelloWorld()
{
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IHelloService, MockHelloService>();
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/");
Assert.Equal("Test Hello", response);
}
class MockHelloService : IHelloService
{
public string HelloMessage => "Test Hello";
}
WebApplicationFactory
を含む .NET 5 バージョンと .NET 6 バージョンは、設計上同じです。
ASP.NET Core