Nguon: Microsoft Learn · .NET 8.0

ASP.NET Core Web Host

Nguồn: ASP.NET Core Web Host

ASP.NET Core app cấu hình và khởi động một host (máy chủ lưu trữ). Host chịu trách nhiệm khởi động ứng dụng và quản lý vòng đời. Tối thiểu, host cấu hình một server và một request processing pipeline (đường dẫn xử lý yêu cầu). Host cũng có thể thiết lập logging (ghi nhật ký), dependency injection và configuration.

Bài viết này đề cập đến Web Host, vẫn còn khả dụng chỉ để tương thích ngược. Các template ASP.NET Core tạo ra WebApplicationBuilderWebApplication, được khuyến nghị cho web app. Để biết thêm thông tin về WebApplicationBuilderWebApplication, xem Migrate from ASP.NET Core in .NET 5 to .NET 6.

Thiết lập host

Tạo một host bằng cách sử dụng instance của IWebHostBuilder. Tác vụ này thường được thực hiện trong entry point của ứng dụng, phương thức Main trong file Program.cs. Một ứng dụng điển hình gọi phương thức CreateDefaultBuilder để bắt đầu thiết lập host:

csharp
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Phương thức CreateDefaultBuilder thực hiện các tác vụ sau:

Content root xác định nơi host tìm kiếm các content file như MVC view file.

Để biết thêm về cấu hình ứng dụng, xem Configuration in ASP.NET Core.

Các phương thức ghi đè cấu hình

Bạn có thể ghi đè và bổ sung cấu hình được định nghĩa bởi CreateDefaultBuilder. Sử dụng các phương thức ConfigureAppConfigurationConfigureLogging, và các phương thức và extension methods khác của IWebHostBuilder.

Ví dụ:

csharp
WebHost.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true);
    })
    ...
csharp
WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logging => 
    {
        logging.SetMinimumLevel(LogLevel.Warning);
    })
    ...
csharp
WebHost.CreateDefaultBuilder(args)
    .ConfigureKestrel((context, options) =>
    {
        options.Limits.MaxRequestBodySize = 20000000;
    });

Đặt các giá trị cấu hình Web Host

Instance WebHostBuilder dựa vào các cách sau để đặt giá trị cấu hình host:

Application name (Tên ứng dụng)

Key: applicationName | Type: string | Default: Tên assembly có entry point của ứng dụng | Biến môi trường: ASPNETCORE_APPLICATIONNAME

csharp
WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName")

Capture startup errors (Bắt lỗi khởi động)

Key: captureStartupErrors | Type: bool | Default: false (nếu chạy Kestrel sau IIS, mặc định là true) | Biến môi trường: ASPNETCORE_CAPTURESTARTUPERRORS

csharp
WebHost.CreateDefaultBuilder(args)
    .CaptureStartupErrors(true)

Content root

Key: contentRoot | Type: string | Default: Thư mục chứa app assembly | Biến môi trường: ASPNETCORE_CONTENTROOT

csharp
WebHost.CreateDefaultBuilder(args)
    .UseContentRoot("c:\\<content-root>")

Detailed errors (Lỗi chi tiết)

Key: detailedErrors | Type: bool | Default: false | Biến môi trường: ASPNETCORE_DETAILEDERRORS

csharp
WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")

Environment (Môi trường)

Đặt môi trường ứng dụng.

Key: environment | Type: string | Default: Production | Biến môi trường: ASPNETCORE_ENVIRONMENT

Môi trường có thể được đặt thành bất kỳ giá trị nào. Các giá trị được định nghĩa bởi framework bao gồm Development, StagingProduction.

csharp
WebHost.CreateDefaultBuilder(args)
    .UseEnvironment(EnvironmentName.Development)

Hosting startup assemblies (Assembly khởi động hosting)

Key: hostingStartupAssemblies | Type: string | Default: Chuỗi rỗng | Biến môi trường: ASPNETCORE_HOSTINGSTARTUPASSEMBLIES

csharp
WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2")

HTTPS port

Key: https_port | Type: string | Default: Không có | Biến môi trường: ASPNETCORE_HTTPS_PORT

csharp
WebHost.CreateDefaultBuilder(args)
    .UseSetting("https_port", "8080")

Prefer hosting URLs (Ưu tiên URL hosting)

Chỉ ra host có nên lắng nghe trên các URL được cấu hình với WebHostBuilder thay vì các URL được cấu hình với implementation IServer.

Key: preferHostingUrls | Type: bool | Default: false | Biến môi trường: ASPNETCORE_PREFERHOSTINGURLS

csharp
WebHost.CreateDefaultBuilder(args)
    .PreferHostingUrls(true)

Prevent hosting startup (Ngăn chặn khởi động hosting)

Ngăn chặn tự động tải các hosting startup assemblies.

Key: preventHostingStartup | Type: bool | Default: false | Biến môi trường: ASPNETCORE_PREVENTHOSTINGSTARTUP

csharp
WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.PreventHostingStartupKey, "true")

Server URLs

Chỉ ra các địa chỉ IP hoặc host addresses với ports và protocols mà server nên lắng nghe requests.

Key: urls | Type: string | Default: http://localhost:5000 | Biến môi trường: ASPNETCORE_URLS

csharp
WebHost.CreateDefaultBuilder(args)
    .UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002")

Shutdown timeout (Thời gian chờ tắt máy)

Chỉ định thời gian chờ để Web Host tắt máy.

Key: shutdownTimeoutSeconds | Type: int | Default: 5 giây | Biến môi trường: ASPNETCORE_SHUTDOWNTIMEOUTSECONDS

csharp
WebHost.CreateDefaultBuilder(args)
    .UseShutdownTimeout(TimeSpan.FromSeconds(10))

Web root

Key: webroot | Type: string | Default: wwwroot | Biến môi trường: ASPNETCORE_WEBROOT

csharp
WebHost.CreateDefaultBuilder(args)
    .UseWebRoot("public")

Ghi đè cấu hình Web Host

Sử dụng configuration in ASP.NET Core để cấu hình Web Host.

Ghi đè cấu hình được cung cấp bởi UseUrls với config hostsettings.json sau đó là command-line argument config:

csharp
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("hostsettings.json", optional: true)
            .AddCommandLine(args)
            .Build();

        return WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5000")
            .UseConfiguration(config)
            .Configure(app =>
            {
                app.Run(context => 
                    context.Response.WriteAsync("Hello, World!"));
            });
    }
}

Nội dung file hostsettings.json:

json
{
    urls: "http://*:5005"
}

Để chỉ định host chạy trên URL cụ thể, giá trị mong muốn có thể được truyền vào từ command prompt:

dotnetcli
dotnet run --urls "http://*:8080"

Quản lý Web Host

Run

Phương thức Run khởi động web app và block calling thread cho đến khi host shutdown:

csharp
host.Run();

Start

Chạy host theo cách non-blocking bằng cách gọi phương thức Start:

csharp
using (host)
{
    host.Start();
    Console.ReadLine();
}

Nếu truyền danh sách URLs vào phương thức Start, nó lắng nghe trên các URLs được chỉ định:

csharp
var urls = new List<string>()
{
    "http://*:5000",
    "http://localhost:5001"
};

var host = new WebHostBuilder()
    .UseKestrel()
    .UseStartup<Startup>()
    .Start(urls.ToArray());

using (host)
{
    Console.ReadLine();
}

Start(RequestDelegate app)

Chạy host với RequestDelegate:

csharp
using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!")))
{
    Console.WriteLine("Use Ctrl-C to shutdown the host...");
    host.WaitForShutdown();
}

Sử dụng interface IWebHostEnvironment

Interface IWebHostEnvironment cung cấp thông tin về web hosting environment của ứng dụng. Sử dụng constructor injection để lấy instance IWebHostEnvironment, sau đó truy cập các thuộc tính và extension methods của nó:

csharp
public class CustomFileReader
{
    private readonly IWebHostEnvironment _env;

    public CustomFileReader(IWebHostEnvironment env)
    {
        _env = env;
    }

    public string ReadFile(string filePath)
    {
        var fileProvider = _env.WebRootFileProvider;
        // Process the file here
    }
}

Một cách tiếp cận dựa trên convention có thể được sử dụng để cấu hình ứng dụng khi khởi động dựa trên môi trường. Hoặc, inject instance IWebHostEnvironment vào constructor Startup để sử dụng trong phương thức ConfigureServices:

csharp
public class Startup
{
    public Startup(IWebHostEnvironment env)
    {
        HostingEnvironment = env;
    }

    public IWebHostEnvironment HostingEnvironment { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        if (HostingEnvironment.IsDevelopment())
        {
            // Development configuration
        }
        else
        {
            // Staging/Production configuration
        }

        var contentRootPath = HostingEnvironment.ContentRootPath;
    }
}

Service IWebHostEnvironment cũng có thể được inject trực tiếp vào phương thức Configure để thiết lập processing pipeline:

csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        // In Development, use the Developer Exception Page
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // In Staging/Production, route exceptions to /error
        app.UseExceptionHandler("/error");
    }

    var contentRootPath = env.ContentRootPath;
}

Sử dụng interface IHostApplicationLifetime

IHostApplicationLifetime cho phép thực hiện các hoạt động post-startup và shutdown. Ba thuộc tính trên interface là cancellation token dùng để đăng ký các phương thức Action định nghĩa các sự kiện startup và shutdown.

Cancellation tokenTrigger
ApplicationStartedHost đã khởi động hoàn toàn.
ApplicationStoppedHost đang hoàn thành graceful shutdown. Tất cả các request dự kiến sẽ được xử lý. Shutdown chặn cho đến khi sự kiện này hoàn thành.
ApplicationStoppingHost đang thực hiện graceful shutdown. Các request vẫn có thể đang trong quá trình xử lý. Shutdown chặn cho đến khi sự kiện này hoàn thành.
csharp
public class Startup
{
    public void Configure(IApplicationBuilder app, IHostApplicationLifetime appLifetime)
    {
        appLifetime.ApplicationStarted.Register(OnStarted);
        appLifetime.ApplicationStopping.Register(OnStopping);
        appLifetime.ApplicationStopped.Register(OnStopped);

        Console.CancelKeyPress += (sender, eventArgs) =>
        {
            appLifetime.StopApplication();
            // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
            eventArgs.Cancel = true;
        };
    }

    private void OnStarted()
    {
        // Perform post-startup activities here
    }

    private void OnStopping()
    {
        // Perform on-stopping activities here
    }

    private void OnStopped()
    {
        // Perform post-stopped activities here
    }
}

Phương thức StopApplication yêu cầu chấm dứt ứng dụng. Class sau sử dụng StopApplication để tắt máy ứng dụng một cách nhẹ nhàng khi phương thức Shutdown của class được gọi:

csharp
public class MyClass
{
    private readonly IHostApplicationLifetime _appLifetime;

    public MyClass(IHostApplicationLifetime appLifetime)
    {
        _appLifetime = appLifetime;
    }

    public void Shutdown()
    {
        _appLifetime.StopApplication();
    }
}

Cấu hình scope validation (xác thực phạm vi)

Phương thức CreateDefaultBuilder đặt thuộc tính ValidateScopes thành true nếu môi trường ứng dụng là Development.

Khi ValidateScopes được đặt thành true, service provider mặc định thực hiện kiểm tra để xác minh:

Để luôn xác thực scopes, bao gồm cả trong môi trường Production, cấu hình đối tượng ServiceProviderOptions với phương thức UseDefaultServiceProvider trên host builder:

csharp
WebHost.CreateDefaultBuilder(args)
    .UseDefaultServiceProvider((context, options) => {
        options.ValidateScopes = true;
    })