최소 API 앱의 WebApplication 및 WebApplicationBuilder

WebApplication

다음 코드는 ASP.NET Core 템플릿에서 생성됩니다.

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

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

app.Run();

위의 코드는 명령줄에서 dotnet new web을 통해 만들거나 Visual Studio에서 빈 웹 템플릿을 선택하여 만들 수 있습니다.

다음 코드는 WebApplicationBuilder를 명시적으로 만들지 않고 WebApplication(app)을 만듭니다.

var app = WebApplication.Create(args);

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

app.Run();

WebApplication.Create는 미리 구성된 기본값을 사용하여 WebApplication 클래스의 새 인스턴스를 초기화합니다.

WebApplication 는 특정 조건에 따라 다음 미들웨어 Minimal API applications 를 자동으로 추가합니다.

  • HostingEnvironment"Development"일 때 UseDeveloperExceptionPage가 먼저 추가됩니다.
  • 사용자 코드가 아직 UseRouting를 호출하지 않은 경우 및 구성된 엔드포인트가 있는 경우(예: app.MapGet), UseRouting가 두 번째로 추가됩니다.
  • UseEndpoints는 엔드포인트가 구성된 경우 미들웨어 파이프라인의 끝에 추가됩니다.
  • UseAuthentication은 사용자 코드가 아직 호출 UseAuthentication 되지 않은 경우와 서비스 공급자에서 검색할 수 있는 경우 IAuthenticationSchemeProvider 즉시 UseRouting 추가됩니다. IAuthenticationSchemeProviderAddAuthentication를 사용할 때 기본적으로 추가되고 IServiceProviderIsService를 사용하여 서비스가 검색됩니다.
  • UseAuthorization 는 사용자 코드가 아직 호출 UseAuthorization 되지 않았고 서비스 공급자에서 검색할 수 있는 경우 IAuthorizationHandlerProvider 다음에 추가됩니다. IAuthorizationHandlerProviderAddAuthorization를 사용할 때 기본적으로 추가되고 IServiceProviderIsService를 사용하여 서비스가 검색됩니다.
  • 사용자 구성 미들웨어 및 엔드포인트는 UseRoutingUseEndpoints 사이에 추가됩니다.

다음 코드는 앱에 추가되는 자동 미들웨어가 생성하는 것입니다.

if (isDevelopment)
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();

if (isAuthenticationConfigured)
{
    app.UseAuthentication();
}

if (isAuthorizationConfigured)
{
    app.UseAuthorization();
}

// user middleware/endpoints
app.CustomMiddleware(...);
app.MapGet("/", () => "hello world");
// end user middleware/endpoints

app.UseEndpoints(e => {});

경우에 따라 앱에 대한 기본 미들웨어 구성이 올바르지 않으며 수정이 필요합니다. 예를 들어, UseCorsUseAuthenticationUseAuthorization 전에 호출되어야 합니다. 앱은 호출 UseAuthentication 해야 하며 UseAuthorization 호출되는 경우 UseCors :

app.UseCors();
app.UseAuthentication();
app.UseAuthorization();

경로 일치가 발생하기 전에 미들웨어를 실행해야 하는 경우, UseRouting를 호출해야 하며 UseRouting에 대한 호출 전에 미들웨어를 배치해야 합니다. UseEndpoints 는 앞에서 설명한 대로 자동으로 추가되므로 이 경우에는 필요하지 않습니다.

app.Use((context, next) =>
{
    return next(context);
});

app.UseRouting();

// other middleware and endpoints

터미널 미들웨어를 추가하는 경우:

  • 미들웨어는 UseEndpoints 다음에 추가해야 합니다.
  • 터미널 미들웨어를 올바른 위치에 배치할 수 있도록 앱은 UseRoutingUseEndpoints를 호출해야 합니다.
app.UseRouting();

app.MapGet("/", () => "hello world");

app.UseEndpoints(e => {});

app.Run(context =>
{
    context.Response.StatusCode = 404;
    return Task.CompletedTask;
});

터미널 미들웨어는 요청을 처리하는 엔드포인트가 없는 경우 실행되는 미들웨어입니다.

포트 작업

Visual Studio 또는 dotnet new를 사용하여 웹앱을 만들면 앱이 응답하는 포트를 지정하는 Properties/launchSettings.json 파일이 만들어집니다. 다음에 오는 포트 설정 샘플에서는 Visual Studio에서 앱을 실행하면 Unable to connect to web server 'AppName' 오류 대화 상자가 반환됩니다. Visual Studio는 Properties/launchSettings.json에 지정된 포트가 예상되기 때문에 오류를 반환하지만 앱은 app.Run("http://localhost:3000")에서 지정한 포트를 사용하고 있습니다. 명령줄에서 다음 포트 변경 샘플을 실행합니다.

다음 섹션에서는 앱이 응답하는 포트를 설정합니다.

var app = WebApplication.Create(args);

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

app.Run("http://localhost:3000");

위의 코드에서 앱은 포트 3000에 응답합니다.

여러 포트

위의 코드에서 앱은 포트 30004000에 응답합니다.

var app = WebApplication.Create(args);

app.Urls.Add("http://localhost:3000");
app.Urls.Add("http://localhost:4000");

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

app.Run();

명령줄에서 포트 설정

다음 명령은 앱이 포트 7777에 응답하도록 합니다.

dotnet run --urls="https://localhost:7777"

Kestrel 엔드포인트가 appsettings.json 파일에도 구성된 경우 appsettings.json 파일에서 지정된 URL이 사용됩니다. 자세한 내용은 Kestrel 엔드포인트 구성을 참조하세요.

환경에서 포트 읽기

다음 코드는 환경에서 포트를 읽습니다.

var app = WebApplication.Create(args);

var port = Environment.GetEnvironmentVariable("PORT") ?? "3000";

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

app.Run($"http://localhost:{port}");

환경에서 포트를 설정하는 기본 방법은 다음 섹션에 나오는 ASPNETCORE_URLS 환경 변수를 사용하는 것입니다.

ASPNETCORE_URLS 환경 변수를 통해 포트 설정

ASPNETCORE_URLS 환경 변수를 사용하여 포트를 설정할 수 있습니다.

ASPNETCORE_URLS=http://localhost:3000

ASPNETCORE_URLS는 여러 URL을 지원합니다.

ASPNETCORE_URLS=http://localhost:3000;https://localhost:5000

환경 사용에 대한 자세한 내용은 ASP.NET Core에서 여러 환경 사용을 참조하세요.

모든 인터페이스에서 수신 대기

다음 샘플은 모든 인터페이스에서의 수신 대기를 보여 줍니다.

http://*:3000

var app = WebApplication.Create(args);

app.Urls.Add("http://*:3000");

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

app.Run();

http://+:3000

var app = WebApplication.Create(args);

app.Urls.Add("http://+:3000");

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

app.Run();

http://0.0.0.0:3000

var app = WebApplication.Create(args);

app.Urls.Add("http://0.0.0.0:3000");

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

app.Run();

ASPNETCORE_URLS를 사용하여 모든 인터페이스에서 수신 대기

이전 샘플은 ASPNETCORE_URLS를 사용할 수 있습니다.

ASPNETCORE_URLS=http://*:3000;https://+:5000;http://0.0.0.0:5005

개발 인증서로 HTTPS 지정

var app = WebApplication.Create(args);

app.Urls.Add("https://localhost:3000");

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

app.Run();

개발 인증서에 대한 자세한 내용은 Windows 및 macOS에서 ASP.NET Core HTTPS 개발 인증서 신뢰를 참조하세요.

사용자 지정 인증서를 사용하여 HTTPS 지정

다음 섹션에서는 파일 및 구성을 통해 사용자 지정 인증서를 지정하는 appsettings.json 방법을 보여 있습니다.

appsettings.json을 사용하여 사용자 지정 인증서 지정

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "Certificates": {
      "Default": {
        "Path": "cert.pem",
        "KeyPath": "key.pem"
      }
    }
  }
}

구성을 통해 사용자 지정 인증서 지정

var builder = WebApplication.CreateBuilder(args);

// Configure the cert and the key
builder.Configuration["Kestrel:Certificates:Default:Path"] = "cert.pem";
builder.Configuration["Kestrel:Certificates:Default:KeyPath"] = "key.pem";

var app = builder.Build();

app.Urls.Add("https://localhost:3000");

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

app.Run();

인증서 API 사용

using System.Security.Cryptography.X509Certificates;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
    options.ConfigureHttpsDefaults(httpsOptions =>
    {
        var certPath = Path.Combine(builder.Environment.ContentRootPath, "cert.pem");
        var keyPath = Path.Combine(builder.Environment.ContentRootPath, "key.pem");

        httpsOptions.ServerCertificate = X509Certificate2.CreateFromPemFile(certPath, 
                                         keyPath);
    });
});

var app = builder.Build();

app.Urls.Add("https://localhost:3000");

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

app.Run();

구성

다음 코드는 구성 시스템에서 읽습니다.

var app = WebApplication.Create(args);

var message = app.Configuration["HelloKey"] ?? "Config failed!";

app.MapGet("/", () => message);

app.Run();

자세한 내용은 ASP.NET Core의 구성을 참조하세요.

로깅

다음 코드는 로그온 애플리케이션 시작에 메시지를 씁니다.

var app = WebApplication.Create(args);

app.Logger.LogInformation("The app started");

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

app.Run();

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

DI(종속성 주입) 컨테이너 액세스

다음 코드에서는 애플리케이션을 시작하는 동안 DI 컨테이너에서 서비스를 가져오는 방법을 보여줍니다.


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddScoped<SampleService>();

var app = builder.Build();

app.MapControllers();

using (var scope = app.Services.CreateScope())
{
    var sampleService = scope.ServiceProvider.GetRequiredService<SampleService>();
    sampleService.DoSomething();
}

app.Run();

자세한 내용은 ASP.NET Core에서 종속성 주입을 참조하세요.

WebApplicationBuilder

이 섹션에는 WebApplicationBuilder를 사용하는 샘플 코드가 포함되어 있습니다.

콘텐츠 루트, 애플리케이션 이름, 환경 변경

다음 코드는 콘텐츠 루트, 애플리케이션 이름, 환경을 설정합니다.

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

WebApplication.CreateBuilder는 미리 구성된 기본값을 사용하여 WebApplicationBuilder 클래스의 새 인스턴스를 초기화합니다.

자세한 내용은 ASP.NET Core 기본 사항 개요를 참조하세요

환경 변수 또는 명령줄을 통해 콘텐츠 루트, 앱 이름, 환경 변경

다음 표는 콘텐츠 루트, 앱 이름, 환경 변경에 사용되는 환경 변수와 명령줄 인수를 보여 줍니다.

기능 환경 변수 명령줄 인수
애플리케이션 이름 ASPNETCORE_APPLICATIONNAME --applicationName
환경 이름 ASPNETCORE_ENVIRONMENT --environment
콘텐츠 루트 ASPNETCORE_CONTENTROOT --contentRoot

구성 공급자 추가

다음 샘플은 INI 구성 공급자를 추가합니다.

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

구성 읽기

기본적으로 WebApplicationBuilder는 다음을 포함하여 여러 원본에서 구성을 읽습니다.

  • appSettings.jsonappSettings.{environment}.json
  • 환경 변수
  • 명령줄

다음 코드는 구성에서 HelloKey를 읽고 / 엔드포인트에 값을 표시합니다. 구성 값이 null이면 "Hello"가 message에 할당됩니다.

var builder = WebApplication.CreateBuilder(args);

var message = builder.Configuration["HelloKey"] ?? "Hello";

var app = builder.Build();

app.MapGet("/", () => message);

app.Run();

구성 소스 읽기의 전체 목록은 ASP.NET Core의 구성에서 기본 구성을 참조하세요.

로깅 공급자 추가

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

app.Run();

서비스 추가

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

IHostBuilder 사용자 지정

IHostBuilder의 기존 확장 메서드는 호스트 속성을 사용하여 액세스할 수 있습니다.

var builder = WebApplication.CreateBuilder(args);

// Wait 30 seconds for graceful shutdown.
builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));

var app = builder.Build();

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

app.Run();

IWebHostBuilder 사용자 지정

IWebHostBuilder의 확장 메서드는 WebApplicationBuilder.WebHost 속성을 사용하여 액세스할 수 있습니다.

var builder = WebApplication.CreateBuilder(args);

// Change the HTTP server implemenation to be HTTP.sys based
builder.WebHost.UseHttpSys();

var app = builder.Build();

app.MapGet("/", () => "Hello HTTP.sys");

app.Run();

웹 루트 변경

기본적으로 웹 루트는 wwwroot 폴더의 콘텐츠 루트를 기준으로 합니다. 웹 루트는 정적 파일 미들웨어가 정적 파일을 찾는 위치입니다. 웹 루트는 WebHostOptions, 명령줄 또는 UseWebRoot 메서드를 사용하여 변경할 수 있습니다.

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    // Look for static files in webroot
    WebRootPath = "webroot"
});

var app = builder.Build();

app.Run();

사용자 지정 DI(종속성 주입) 컨테이너

다음 예제에서는 Autofac을 사용합니다.

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

미들웨어 추가

기존 ASP.NET Core 미들웨어는 WebApplication에서 구성할 수 있습니다.

var app = WebApplication.Create(args);

// Setup the file server to serve static files.
app.UseFileServer();

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

app.Run();

자세한 내용은 ASP.NET Core 미들웨어를 참조하세요.

개발자 예외 페이지

WebApplication.CreateBuilder는 미리 구성된 기본값을 사용하여 WebApplicationBuilder 클래스의 새 인스턴스를 초기화합니다. 개발자 예외 페이지는 미리 구성된 기본값에서 사용하도록 설정됩니다. 개발 환경에서 다음 코드가 실행되는 경우 /로 이동하면 예외를 보여 주는 친숙한 페이지가 렌더링됩니다.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () =>
{
    throw new InvalidOperationException("Oops, the '/' route has thrown an exception.");
});

app.Run();

WebApplication

다음 코드는 ASP.NET Core 템플릿에서 생성됩니다.

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

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

app.Run();

위의 코드는 명령줄에서 dotnet new web을 통해 만들거나 Visual Studio에서 빈 웹 템플릿을 선택하여 만들 수 있습니다.

다음 코드는 WebApplicationBuilder를 명시적으로 만들지 않고 WebApplication(app)을 만듭니다.

var app = WebApplication.Create(args);

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

app.Run();

WebApplication.Create는 미리 구성된 기본값을 사용하여 WebApplication 클래스의 새 인스턴스를 초기화합니다.

WebApplication 는 특정 조건에 따라 다음 미들웨어 Minimal API applications 를 자동으로 추가합니다.

  • HostingEnvironment"Development"일 때 UseDeveloperExceptionPage가 먼저 추가됩니다.
  • 사용자 코드가 아직 UseRouting를 호출하지 않은 경우 및 구성된 엔드포인트가 있는 경우(예: app.MapGet), UseRouting가 두 번째로 추가됩니다.
  • UseEndpoints는 엔드포인트가 구성된 경우 미들웨어 파이프라인의 끝에 추가됩니다.
  • UseAuthentication은 사용자 코드가 아직 호출 UseAuthentication 되지 않은 경우와 서비스 공급자에서 검색할 수 있는 경우 IAuthenticationSchemeProvider 즉시 UseRouting 추가됩니다. IAuthenticationSchemeProviderAddAuthentication를 사용할 때 기본적으로 추가되고 IServiceProviderIsService를 사용하여 서비스가 검색됩니다.
  • UseAuthorization 는 사용자 코드가 아직 호출 UseAuthorization 되지 않았고 서비스 공급자에서 검색할 수 있는 경우 IAuthorizationHandlerProvider 다음에 추가됩니다. IAuthorizationHandlerProviderAddAuthorization를 사용할 때 기본적으로 추가되고 IServiceProviderIsService를 사용하여 서비스가 검색됩니다.
  • 사용자 구성 미들웨어 및 엔드포인트는 UseRoutingUseEndpoints 사이에 추가됩니다.

다음 코드는 앱에 추가되는 자동 미들웨어가 생성하는 것입니다.

if (isDevelopment)
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();

if (isAuthenticationConfigured)
{
    app.UseAuthentication();
}

if (isAuthorizationConfigured)
{
    app.UseAuthorization();
}

// user middleware/endpoints
app.CustomMiddleware(...);
app.MapGet("/", () => "hello world");
// end user middleware/endpoints

app.UseEndpoints(e => {});

경우에 따라 앱에 대한 기본 미들웨어 구성이 올바르지 않으며 수정이 필요합니다. 예를 들어, UseCorsUseAuthenticationUseAuthorization 전에 호출되어야 합니다. 앱은 호출 UseAuthentication 해야 하며 UseAuthorization 호출되는 경우 UseCors :

app.UseCors();
app.UseAuthentication();
app.UseAuthorization();

경로 일치가 발생하기 전에 미들웨어를 실행해야 하는 경우, UseRouting를 호출해야 하며 UseRouting에 대한 호출 전에 미들웨어를 배치해야 합니다. UseEndpoints 는 앞에서 설명한 대로 자동으로 추가되므로 이 경우에는 필요하지 않습니다.

app.Use((context, next) =>
{
    return next(context);
});

app.UseRouting();

// other middleware and endpoints

터미널 미들웨어를 추가하는 경우:

  • 미들웨어는 UseEndpoints 다음에 추가해야 합니다.
  • 터미널 미들웨어를 올바른 위치에 배치할 수 있도록 앱은 UseRoutingUseEndpoints를 호출해야 합니다.
app.UseRouting();

app.MapGet("/", () => "hello world");

app.UseEndpoints(e => {});

app.Run(context =>
{
    context.Response.StatusCode = 404;
    return Task.CompletedTask;
});

터미널 미들웨어는 요청을 처리하는 엔드포인트가 없는 경우 실행되는 미들웨어입니다.

포트 작업

Visual Studio 또는 dotnet new를 사용하여 웹앱을 만들면 앱이 응답하는 포트를 지정하는 Properties/launchSettings.json 파일이 만들어집니다. 다음에 오는 포트 설정 샘플에서는 Visual Studio에서 앱을 실행하면 Unable to connect to web server 'AppName' 오류 대화 상자가 반환됩니다. Visual Studio는 Properties/launchSettings.json에 지정된 포트가 예상되기 때문에 오류를 반환하지만 앱은 app.Run("http://localhost:3000")에서 지정한 포트를 사용하고 있습니다. 명령줄에서 다음 포트 변경 샘플을 실행합니다.

다음 섹션에서는 앱이 응답하는 포트를 설정합니다.

var app = WebApplication.Create(args);

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

app.Run("http://localhost:3000");

위의 코드에서 앱은 포트 3000에 응답합니다.

여러 포트

위의 코드에서 앱은 포트 30004000에 응답합니다.

var app = WebApplication.Create(args);

app.Urls.Add("http://localhost:3000");
app.Urls.Add("http://localhost:4000");

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

app.Run();

명령줄에서 포트 설정

다음 명령은 앱이 포트 7777에 응답하도록 합니다.

dotnet run --urls="https://localhost:7777"

Kestrel 엔드포인트가 appsettings.json 파일에도 구성된 경우 appsettings.json 파일에서 지정된 URL이 사용됩니다. 자세한 내용은 Kestrel 엔드포인트 구성을 참조하세요.

환경에서 포트 읽기

다음 코드는 환경에서 포트를 읽습니다.

var app = WebApplication.Create(args);

var port = Environment.GetEnvironmentVariable("PORT") ?? "3000";

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

app.Run($"http://localhost:{port}");

환경에서 포트를 설정하는 기본 방법은 다음 섹션에 나오는 ASPNETCORE_URLS 환경 변수를 사용하는 것입니다.

ASPNETCORE_URLS 환경 변수를 통해 포트 설정

ASPNETCORE_URLS 환경 변수를 사용하여 포트를 설정할 수 있습니다.

ASPNETCORE_URLS=http://localhost:3000

ASPNETCORE_URLS는 여러 URL을 지원합니다.

ASPNETCORE_URLS=http://localhost:3000;https://localhost:5000

모든 인터페이스에서 수신 대기

다음 샘플은 모든 인터페이스에서의 수신 대기를 보여 줍니다.

http://*:3000

var app = WebApplication.Create(args);

app.Urls.Add("http://*:3000");

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

app.Run();

http://+:3000

var app = WebApplication.Create(args);

app.Urls.Add("http://+:3000");

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

app.Run();

http://0.0.0.0:3000

var app = WebApplication.Create(args);

app.Urls.Add("http://0.0.0.0:3000");

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

app.Run();

ASPNETCORE_URLS를 사용하여 모든 인터페이스에서 수신 대기

이전 샘플은 ASPNETCORE_URLS를 사용할 수 있습니다.

ASPNETCORE_URLS=http://*:3000;https://+:5000;http://0.0.0.0:5005

ASPNETCORE_HTTPS_PORTS 사용하여 모든 인터페이스에서 수신 대기

위의 샘플은 사용할 ASPNETCORE_HTTPS_PORTS 수 있습니다.ASPNETCORE_HTTP_PORTS

ASPNETCORE_HTTP_PORTS=3000;5005
ASPNETCORE_HTTPS_PORTS=5000

자세한 내용은 ASP.NET Core Kestrel 웹 서버에 대한 엔드포인트 구성을 참조하세요.

개발 인증서로 HTTPS 지정

var app = WebApplication.Create(args);

app.Urls.Add("https://localhost:3000");

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

app.Run();

개발 인증서에 대한 자세한 내용은 Windows 및 macOS에서 ASP.NET Core HTTPS 개발 인증서 신뢰를 참조하세요.

사용자 지정 인증서를 사용하여 HTTPS 지정

다음 섹션에서는 파일 및 구성을 통해 사용자 지정 인증서를 지정하는 appsettings.json 방법을 보여 있습니다.

appsettings.json을 사용하여 사용자 지정 인증서 지정

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "Certificates": {
      "Default": {
        "Path": "cert.pem",
        "KeyPath": "key.pem"
      }
    }
  }
}

구성을 통해 사용자 지정 인증서 지정

var builder = WebApplication.CreateBuilder(args);

// Configure the cert and the key
builder.Configuration["Kestrel:Certificates:Default:Path"] = "cert.pem";
builder.Configuration["Kestrel:Certificates:Default:KeyPath"] = "key.pem";

var app = builder.Build();

app.Urls.Add("https://localhost:3000");

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

app.Run();

인증서 API 사용

using System.Security.Cryptography.X509Certificates;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
    options.ConfigureHttpsDefaults(httpsOptions =>
    {
        var certPath = Path.Combine(builder.Environment.ContentRootPath, "cert.pem");
        var keyPath = Path.Combine(builder.Environment.ContentRootPath, "key.pem");

        httpsOptions.ServerCertificate = X509Certificate2.CreateFromPemFile(certPath, 
                                         keyPath);
    });
});

var app = builder.Build();

app.Urls.Add("https://localhost:3000");

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

app.Run();

환경 읽기

var app = WebApplication.Create(args);

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/oops");
}

app.MapGet("/", () => "Hello World");
app.MapGet("/oops", () => "Oops! An error happened.");

app.Run();

환경 사용에 대한 자세한 내용은 ASP.NET Core에서 여러 환경 사용을 참조하세요.

구성

다음 코드는 구성 시스템에서 읽습니다.

var app = WebApplication.Create(args);

var message = app.Configuration["HelloKey"] ?? "Config failed!";

app.MapGet("/", () => message);

app.Run();

자세한 내용은 ASP.NET Core의 구성을 참조하세요.

로깅

다음 코드는 로그온 애플리케이션 시작에 메시지를 씁니다.

var app = WebApplication.Create(args);

app.Logger.LogInformation("The app started");

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

app.Run();

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

DI(종속성 주입) 컨테이너 액세스

다음 코드에서는 애플리케이션을 시작하는 동안 DI 컨테이너에서 서비스를 가져오는 방법을 보여줍니다.


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddScoped<SampleService>();

var app = builder.Build();

app.MapControllers();

using (var scope = app.Services.CreateScope())
{
    var sampleService = scope.ServiceProvider.GetRequiredService<SampleService>();
    sampleService.DoSomething();
}

app.Run();

다음 코드에서는 특성을 사용하여 DI 컨테이너에서 키에 액세스하는 [FromKeyedServices] 방법을 보여 있습니다.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");

var app = builder.Build();

app.MapGet("/big", ([FromKeyedServices("big")] ICache bigCache) => bigCache.Get("date"));

app.MapGet("/small", ([FromKeyedServices("small")] ICache smallCache) => smallCache.Get("date"));

app.Run();

public interface ICache
{
    object Get(string key);
}
public class BigCache : ICache
{
    public object Get(string key) => $"Resolving {key} from big cache.";
}

public class SmallCache : ICache
{
    public object Get(string key) => $"Resolving {key} from small cache.";
}

DI에 대한 자세한 내용은 ASP.NET Core의 종속성 주입을 참조 하세요.

WebApplicationBuilder

이 섹션에는 WebApplicationBuilder를 사용하는 샘플 코드가 포함되어 있습니다.

콘텐츠 루트, 애플리케이션 이름, 환경 변경

다음 코드는 콘텐츠 루트, 애플리케이션 이름, 환경을 설정합니다.

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

WebApplication.CreateBuilder는 미리 구성된 기본값을 사용하여 WebApplicationBuilder 클래스의 새 인스턴스를 초기화합니다.

자세한 내용은 ASP.NET Core 기본 사항 개요를 참조하세요

환경 변수 또는 명령줄을 사용하여 콘텐츠 루트, 앱 이름 및 환경 변경

다음 표는 콘텐츠 루트, 앱 이름, 환경 변경에 사용되는 환경 변수와 명령줄 인수를 보여 줍니다.

기능 환경 변수 명령줄 인수
애플리케이션 이름 ASPNETCORE_APPLICATIONNAME --applicationName
환경 이름 ASPNETCORE_ENVIRONMENT --environment
콘텐츠 루트 ASPNETCORE_CONTENTROOT --contentRoot

구성 공급자 추가

다음 샘플은 INI 구성 공급자를 추가합니다.

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

구성 읽기

기본적으로 WebApplicationBuilder는 다음을 포함하여 여러 원본에서 구성을 읽습니다.

  • appSettings.jsonappSettings.{environment}.json
  • 환경 변수
  • 명령줄

읽은 구성 원본의 전체 목록은 ASP.NET Core의 구성에서 기본 구성을 참조하세요.

다음 코드는 구성에서 HelloKey를 읽고 / 엔드포인트에 값을 표시합니다. 구성 값이 null이면 "Hello"가 message에 할당됩니다.

var builder = WebApplication.CreateBuilder(args);

var message = builder.Configuration["HelloKey"] ?? "Hello";

var app = builder.Build();

app.MapGet("/", () => message);

app.Run();

환경 읽기

var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsDevelopment())
{
    Console.WriteLine($"Running in development.");
}

var app = builder.Build();

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

app.Run();

로깅 공급자 추가

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

app.Run();

서비스 추가

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

IHostBuilder 사용자 지정

IHostBuilder의 기존 확장 메서드는 호스트 속성을 사용하여 액세스할 수 있습니다.

var builder = WebApplication.CreateBuilder(args);

// Wait 30 seconds for graceful shutdown.
builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));

var app = builder.Build();

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

app.Run();

IWebHostBuilder 사용자 지정

IWebHostBuilder의 확장 메서드는 WebApplicationBuilder.WebHost 속성을 사용하여 액세스할 수 있습니다.

var builder = WebApplication.CreateBuilder(args);

// Change the HTTP server implemenation to be HTTP.sys based
builder.WebHost.UseHttpSys();

var app = builder.Build();

app.MapGet("/", () => "Hello HTTP.sys");

app.Run();

웹 루트 변경

기본적으로 웹 루트는 wwwroot 폴더의 콘텐츠 루트를 기준으로 합니다. 웹 루트는 정적 파일 미들웨어가 정적 파일을 찾는 위치입니다. 웹 루트는 WebHostOptions, 명령줄 또는 UseWebRoot 메서드를 사용하여 변경할 수 있습니다.

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    // Look for static files in webroot
    WebRootPath = "webroot"
});

var app = builder.Build();

app.Run();

사용자 지정 DI(종속성 주입) 컨테이너

다음 예제에서는 Autofac을 사용합니다.

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

미들웨어 추가

기존 ASP.NET Core 미들웨어는 WebApplication에서 구성할 수 있습니다.

var app = WebApplication.Create(args);

// Setup the file server to serve static files.
app.UseFileServer();

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

app.Run();

자세한 내용은 ASP.NET Core 미들웨어를 참조하세요.

개발자 예외 페이지

WebApplication.CreateBuilder는 미리 구성된 기본값을 사용하여 WebApplicationBuilder 클래스의 새 인스턴스를 초기화합니다. 개발자 예외 페이지는 미리 구성된 기본값에서 사용하도록 설정됩니다. 개발 환경에서 다음 코드가 실행되는 경우 /로 이동하면 예외를 보여 주는 친숙한 페이지가 렌더링됩니다.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () =>
{
    throw new InvalidOperationException("Oops, the '/' route has thrown an exception.");
});

app.Run();