ASP.NET Core 6.0의 새로운 최소 호스팅 모델로 마이그레이션된 코드 샘플

이 문서에서는 ASP.NET Core 6.0으로 마이그레이션된 코드 샘플을 제공합니다. ASP.NET Core 6.0은 새로운 최소 호스팅 모델을 사용합니다. 자세한 내용은 새 호스팅 모델을 참조하세요.

미들웨어

다음 코드는 정적 파일 미들웨어를 ASP.NET Core 5 앱에 추가합니다.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();
    }
}

다음 코드는 정적 파일 미들웨어를 ASP.NET Core 6 앱에 추가합니다.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseStaticFiles();

app.Run();

WebApplication.CreateBuilder는 미리 구성된 기본값을 사용하여 WebApplicationBuilder 클래스의 새 인스턴스를 초기화합니다. 자세한 내용은 ASP.NET Core 미들웨어를 참조하세요.

라우팅

다음 코드는 ASP.NET Core 5 앱에 엔드포인트를 추가합니다.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", () => "Hello World");
        });
    }
}

.NET 6에서는 UseEndpoints 또는 UseRouting에 대한 명시적 호출 없이 경로가 WebApplication에 직접 추가될 수 있습니다. 다음 코드는 ASP.NET Core 6 앱에 엔드포인트를 추가합니다.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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

app.Run();

참고:WebApplication에 직접 추가된 경로는 파이프라인의 끝에서 실행됩니다.

콘텐츠 루트, 앱 이름 및 환경 변경

ASP.NET Core 5

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);
        });

ASP.NET Core 6

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 --environment
콘텐츠 루트 ASPNETCORE_CONTENTROOT --contentRoot

구성 공급자 추가

ASP.NET Core 5

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(config =>
        {
            config.AddIniFile("appsettings.ini");
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

ASP.NET Core 6

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddIniFile("appsettings.ini");

var app = builder.Build();

자세한 내용은 ASP.NET Core의 구성에서 파일 구성 공급자를 참조하세요.

로깅 공급자 추가

ASP.NET Core 5

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.AddJsonConsole();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

ASP.NET Core 6

var builder = WebApplication.CreateBuilder(args);

// Configure JSON logging to the console.
builder.Logging.AddJsonConsole();

var app = builder.Build();

자세한 내용은 .NET Core 및 ASP.NET Core의 로깅을 참조하세요.

서비스 추가

ASP.NET Core 5

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add the memory cache services
        services.AddMemoryCache();

        // Add a custom scoped service
        services.AddScoped<ITodoRepository, TodoRepository>();
    }
}

ASP.NET Core 6

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 사용자 지정

ASP.NET Core 5

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

ASP.NET Core 6

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 사용자 지정

ASP.NET Core 5

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>();
        });

ASP.NET Core 6

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 폴더의 콘텐츠 루트를 기준으로 합니다. 웹 루트는 정적 파일 미들웨어가 정적 파일을 찾는 위치입니다. WebApplicationOptions에서 WebRootPath속성을 설정하여 웹 루트를 변경할 수 있습니다.

ASP.NET Core 5

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            // Look for static files in webroot.
            webBuilder.UseWebRoot("webroot")
                      .UseStartup<Startup>();
        });

ASP.NET Core 6

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을 사용합니다.

ASP.NET Core 5

프로그램 클래스

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Startup 클래스

public class Startup
{
    public void ConfigureContainer(ContainerBuilder containerBuilder)
    {
    }
}

ASP.NET Core 6

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.ConfigureIServiceCollection을 통해 추가된 모든 서비스를 삽입할 수 있습니다.

ASP.NET Core 5

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));
    }
}

ASP.NET Core 6

ASP.NET Core 6에서:

  • WebApplication에서 최상위 속성으로 사용할 수 있는 일반적인 서비스가 몇 가지 있습니다.
  • 추가 서비스는 WebApplication.Services를 통해 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로 테스트

ASP.NET Core 5

다음 샘플에서 테스트 프로젝트는 TestServerWebApplicationFactory<TEntryPoint>를 사용합니다. 이러한 패키지는 명시적 참조가 필요한 별도의 패키지로 배송됩니다.

WebApplicationFactory

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="{Version}" />
</ItemGroup>

TestServer

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="{Version}" />
</ItemGroup>

ASP.NET Core 5 코드

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";
}

ASP.NET Core 6


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 버전은 설계 상 동일합니다.