이 문서에서는 .NET 6의 ASP.NET Core로 마이그레이션된 코드 샘플을 제공합니다. .NET 6의 ASP.NET Core는 새로운 최소 호스팅 모델을 사용합니다. 자세한 내용은 새 호스팅 모델을 참조하세요.
미들웨어(Middleware)
다음 코드는 .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 | --애플리케이션이름 |
환경 이름 | ASPNETCORE_ENVIRONMENT (ASP.NET Core 환경 설정) | --환경 |
콘텐츠 루트 | ASPNETCORE_CONTENTROOT | --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();
웹 루트 변경
기본적으로 웹 루트는 wwwroot
폴더의 콘텐츠 루트를 기준으로 합니다. 웹 루트는 정적 파일 미들웨어가 정적 파일을 찾는 위치입니다. 속성을 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
프로그램 클래스
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";
}
.NET 5 버전과 .NET 6 버전은 WebApplicationFactory
디자인상 동일합니다.
ASP.NET Core