ASP.NET Core 基础知识ASP.NET Core fundamentals

本文概述了了解如何开发 ASP.NET Core 应用的关键主题。This article is an overview of key topics for understanding how to develop ASP.NET Core apps.

Startup 类The Startup class

Startup 类位于:The Startup class is where:

  • 已配置应用所需的任何服务。Any services required by the app are configured.

  • 已定义请求处理管道。The request handling pipeline is defined.

  • 将配置(或注册)服务的代码添加到 Startup.ConfigureServices 方法中。Code to configure (or register) services is added to the Startup.ConfigureServices method. 服务是应用使用的组件。Services are components that are used by the app. 例如,Entity Framework Core 上下文对象是一项服务。For example, an Entity Framework Core context object is a service.

  • 将配置请求处理管道的代码添加到 Startup.Configure 方法中。Code to configure the request handling pipeline is added to the Startup.Configure method. 管道由一系列中间件组件组成。The pipeline is composed as a series of middleware components. 例如,中间件可能处理对静态文件的请求或将 HTTP 请求重定向到 HTTPS。For example, a middleware might handle requests for static files or redirect HTTP requests to HTTPS. 每个中间件在 HttpContext 上执行异步操作,然后调用管道中的下一个中间件或终止请求。Each middleware performs asynchronous operations on an HttpContext and then either invokes the next middleware in the pipeline or terminates the request.

下面是 Startup 类示例:Here's a sample Startup class:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<MovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MovieDb")));
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc();
    }
}

有关更多信息,请参见ASP.NET Core 中的应用启动For more information, see ASP.NET Core 中的应用启动.

依赖关系注入(服务)Dependency injection (services)

ASP.NET Core 有内置的依赖关系注入 (DI) 框架,可使配置的服务适用于应用的类。ASP.NET Core has a built-in dependency injection (DI) framework that makes configured services available to an app's classes. 在类中获取服务实例的一种方法是使用所需类型的参数创建构造函数。One way to get an instance of a service in a class is to create a constructor with a parameter of the required type. 参数可以是服务类型或接口。The parameter can be the service type or an interface. DI 系统在运行时提供服务。The DI system provides the service at runtime.

下面是使用 DI 获取 Entity Framework Core 上下文对象的类。Here's a class that uses DI to get an Entity Framework Core context object. 突出显示的行是构造函数注入的示例:The highlighted line is an example of constructor injection:

public class IndexModel : PageModel
{
    private readonly RazorPagesMovieContext _context;

    public IndexModel(RazorPagesMovieContext context)
    {
        _context = context;
    }
    // ...
    public async Task OnGetAsync()
    {
        var movies = from m in _context.Movies
                        select m;
        Movies = await movies.ToListAsync();
    }
}

虽然 DI 是内置的,但旨在允许插入第三方控制反转 (IoC) 容器(根据需要)。While DI is built in, it's designed to let you plug in a third-party Inversion of Control (IoC) container if you prefer.

有关更多信息,请参见在 ASP.NET Core 依赖注入For more information, see 在 ASP.NET Core 依赖注入.

中间件Middleware

请求处理管道由一系列中间件组件组成。The request handling pipeline is composed as a series of middleware components. 每个组件在 HttpContext 上执行异步操作,然后调用管道中的下一个中间件或终止请求。Each component performs asynchronous operations on an HttpContext and then either invokes the next middleware in the pipeline or terminates the request.

按照惯例,通过在 Startup.Configure 方法中调用其 Use... 扩展方法,向管道添加中间件组件。By convention, a middleware component is added to the pipeline by invoking its Use... extension method in the Startup.Configure method. 例如,要启用静态文件的呈现,请调用 UseStaticFilesFor example, to enable rendering of static files, call UseStaticFiles.

以下示例中突出显示的代码配置请求处理管道:The highlighted code in the following example configures the request handling pipeline:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<MovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MovieDb")));
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc();
    }
}

ASP.NET Core 包含一组丰富的内置中间件,并且你也可以编写自定义中间件。ASP.NET Core includes a rich set of built-in middleware, and you can write custom middleware.

有关更多信息,请参见ASP.NET Core 中间件For more information, see ASP.NET Core 中间件.

主机The host

ASP.NET Core 应用在启动时构建主机。An ASP.NET Core app builds a host on startup. 主机是封装所有应用资源的对象,例如:The host is an object that encapsulates all of the app's resources, such as:

  • HTTP 服务器实现An HTTP server implementation
  • 中间件组件Middleware components
  • 日志记录Logging
  • DIDI
  • ConfigurationConfiguration

一个对象中包含所有应用的相互依赖资源的主要原因是生存期管理:控制应用启动和正常关闭。The main reason for including all of the app's interdependent resources in one object is lifetime management: control over app startup and graceful shutdown.

创建主机的代码位于 Program.Main 中,并遵循生成器模式The code to create a host is in Program.Main and follows the builder pattern. 调用方法来配置属于主机的每个资源。Methods are called to configure each resource that is part of the host. 调用生成器方法以拉取其所有内容并实例化该主机对象。A builder method is called to pull it all together and instantiate the host object.

CreateHostBuilder 是向外部组件(如实体框架)标识生成器方法的特殊名称。CreateHostBuilder is special name that identifies the builder method to external components, such as Entity Framework.

在 ASP.NET Core 3.0 或更高版本中,可在 Web 应用中使用泛型主机(Host 类)或 Web 主机(WebHost 类)。In ASP.NET Core 3.0 or later, Generic Host (Host class) or Web Host (WebHost class) can be used in a web app. 建议使用泛型主机,并且 Web 主机可提供后向兼容性。Generic Host is recommended, and Web Host is available for backwards compatibility.

该框架提供了 CreateDefaultBuilderConfigureWebHostDefaults 方法,用于设置具有常用选项的主机,例如:The framework provides the CreateDefaultBuilder and ConfigureWebHostDefaults methods to set up a host with commonly used options, such as the following:

  • Kestrel 用作 Web 服务器并启用 IIS 集成。Use Kestrel as the web server and enable IIS integration.
  • 从 appsettings.json、appsettings.[EnvironmentName].json、环境变量、命令行参数和其他配置源中加载配置。Load configuration from appsettings.json, appsettings.{Environment Name}.json, environment variables, command line arguments, and other configuration sources.
  • 将日志记录输出发送到控制台并调试提供程序。Send logging output to the console and debug providers.

以下是构建主机的示例代码。Here's sample code that builds a host. 使用常用选项设置主机的方法已突出显示:The methods that set up the host with commonly used options are highlighted:

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

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

有关详细信息,请参阅 .NET 通用主机ASP.NET Core Web 主机For more information, see .NET 通用主机 and ASP.NET Core Web 主机.

CreateWebHostBuilder 是向外部组件(如实体框架)标识生成器方法的特殊名称。CreateWebHostBuilder is special name that identifies the builder method to external components, such as Entity Framework.

ASP.NET Core 2.x 对 Web 应用使用 Web 主机(WebHost 类)。ASP.NET Core 2.x uses Web Host (WebHost class) for web apps. 该框架提供了 CreateDefaultBuilder,用于设置具有常用选项的主机,例如:The framework provides CreateDefaultBuilder to set up a host with commonly used options, such as the following:

  • Kestrel 用作 Web 服务器并启用 IIS 集成。Use Kestrel as the web server and enable IIS integration.
  • 从 appsettings.json、appsettings.[EnvironmentName].json、环境变量、命令行参数和其他配置源中加载配置。Load configuration from appsettings.json, appsettings.{Environment Name}.json, environment variables, command line arguments, and other configuration sources.
  • 将日志记录输出发送到控制台并调试提供程序。Send logging output to the console and debug providers.

以下是构建主机的示例代码:Here's sample code that builds a host:

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

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

有关更多信息,请参见ASP.NET Core Web 主机For more information, see ASP.NET Core Web 主机.

高级主机方案Advanced host scenarios

泛型主机可供任何 .NET Core 应用使用,而不仅仅是 ASP.NET Core 应用。Generic Host is available for any .NET Core app to use—not just ASP.NET Core apps. 使用泛型主机(Host 类),其他类型的应用可以使用各种框架扩展(例如,日志记录、DI、配置和应用生命周期管理)。Generic Host (Host class) allows other types of apps to use cross-cutting framework extensions, such as logging, DI, configuration, and app lifetime management. 有关更多信息,请参见.NET 通用主机For more information, see .NET 通用主机.

Web 主机旨在包含 HTTP 服务器实现,这是其他类型的 .NET 应用所不需要的。Web Host is designed to include an HTTP server implementation, which isn't required for other kinds of .NET apps. 自 ASP.NET Core 2.1 起,泛型主机(Host 类)可供任何 .NET Core 应用使用,而不仅仅是 ASP.NET Core 应用。Starting in ASP.NET Core 2.1, the Generic Host (Host class) is available for any .NET Core app to use—not just ASP.NET Core apps. 使用泛型主机,其他类型的应用可以使用各种框架扩展(例如,日志记录、DI、配置和应用生命周期管理)。Generic Host allows other types of apps to use cross-cutting framework extensions, such as logging, DI, configuration, and app lifetime management. 有关更多信息,请参见.NET 通用主机For more information, see .NET 通用主机.

还可以使用主机运行后台任务。You can also use the host to run background tasks. 有关更多信息,请参见在 ASP.NET Core 中使用托管服务实现后台任务For more information, see 在 ASP.NET Core 中使用托管服务实现后台任务.

服务器Servers

ASP.NET Core 应用使用 HTTP 服务器实现侦听 HTTP 请求。An ASP.NET Core app uses an HTTP server implementation to listen for HTTP requests. 服务器对应用的请求在表面上呈现为一组由 HttpContext 组成的请求功能The server surfaces requests to the app as a set of request features composed into an HttpContext.

ASP.NET Core 提供以下服务器实现:ASP.NET Core provides the following server implementations:

  • Kestrel 是跨平台 Web 服务器。Kestrel is a cross-platform web server. Kestrel 通常使用 IIS 在反向代理配置中运行。Kestrel is often run in a reverse proxy configuration using IIS. 在 ASP.NET Core 2.0 或更高版本中,Kestrel 可作为面向公众的边缘服务器运行,直接向 Internet 公开。In ASP.NET Core 2.0 or later, Kestrel can be run as a public-facing edge server exposed directly to the Internet.
  • IIS HTTP 服务器是适用于使用 IIS 的 Windows 的服务器。IIS HTTP Server is a server for windows that uses IIS. 借助此服务器,ASP.NET Core 应用和 IIS 在同一进程中运行。With this server, the ASP.NET Core app and IIS run in the same process.
  • HTTP.sys是适用于不与 IIS 一起使用的 Windows 的服务器。HTTP.sys is a server for Windows that isn't used with IIS.

ASP.NET Core 提供以下服务器实现:ASP.NET Core provides the following server implementations:

  • Kestrel 是跨平台 Web 服务器。Kestrel is a cross-platform web server. Kestrel 通常使用 IIS 在反向代理配置中运行。Kestrel is often run in a reverse proxy configuration using IIS. 在 ASP.NET Core 2.0 或更高版本中,Kestrel 可作为面向公众的边缘服务器运行,直接向 Internet 公开。In ASP.NET Core 2.0 or later, Kestrel can be run as a public-facing edge server exposed directly to the Internet.
  • HTTP.sys是适用于不与 IIS 一起使用的 Windows 的服务器。HTTP.sys is a server for Windows that isn't used with IIS.

有关更多信息,请参见ASP.NET Core 中的 Web 服务器实现For more information, see ASP.NET Core 中的 Web 服务器实现.

ConfigurationConfiguration

ASP.NET Core 提供了配置框架,可以从配置提供程序的有序集中将设置作为名称/值对。ASP.NET Core provides a configuration framework that gets settings as name-value pairs from an ordered set of configuration providers. 有适用于各种源的内置配置提供程序,例如 .json 文件、.xml 文件、环境变量和命令行参数。There are built-in configuration providers for a variety of sources, such as .json files, .xml files, environment variables, and command-line arguments. 此外可以编写自定义配置提供程序。You can also write custom configuration providers.

例如,可以指定配置来自 appsettings.json 和环境变量。For example, you could specify that configuration comes from appsettings.json and environment variables. 然后,当请求 ConnectionString 的值时,框架首先在 appsettings.json 文件中查找。Then when the value of ConnectionString is requested, the framework looks first in the appsettings.json file. 如果也在环境变量中找到了值,那么来自环境变量的值将优先使用。If the value is found there but also in an environment variable, the value from the environment variable would take precedence.

为了管理密码等机密配置数据,ASP.NET Core 提供了机密管理器工具For managing confidential configuration data such as passwords, ASP.NET Core provides a Secret Manager tool. 对于生产机密,建议使用 Azure 密钥保管库For production secrets, we recommend Azure Key Vault.

有关更多信息,请参见ASP.NET Core 中的配置For more information, see ASP.NET Core 中的配置.

选项Options

在可能的情况下,ASP.NET Core 按照选项模式来存储和检索配置值。Where possible, ASP.NET Core follows the options pattern for storing and retrieving configuration values. 选项模式使用类来表示相关设置的组。The options pattern uses classes to represent groups of related settings.

例如,以下代码可以设置 WebSocket 选项:For example, the following code sets WebSockets options:

var options = new WebSocketOptions  
{  
   KeepAliveInterval = TimeSpan.FromSeconds(120),  
   ReceiveBufferSize = 4096
};  
app.UseWebSockets(options);

有关更多信息,请参见ASP.NET Core 中的选项模式For more information, see ASP.NET Core 中的选项模式.

环境Environments

执行环境(例如“开发”、“暂存”和“生产”)是 ASP.NET Core 中的高级概念。Execution environments, such as Development, Staging, and Production, are a first-class notion in ASP.NET Core. 可以通过设置 ASPNETCORE_ENVIRONMENT 环境变量来指定运行应用的环境。You can specify the environment an app is running in by setting the ASPNETCORE_ENVIRONMENT environment variable. ASP.NET Core 在应用启动时读取该环境变量,并将该值存储在 IHostingEnvironment 实现中。ASP.NET Core reads that environment variable at app startup and stores the value in an IHostingEnvironment implementation. 可通过 DI 在应用的任何位置使用环境对象。The environment object is available anywhere in the app via DI.

以下来自 Startup 类的示例代码将应用配置为仅在开发过程中运行时提供详细的错误信息:The following sample code from the Startup class configures the app to provide detailed error information only when it runs in development:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseMvc();
}

有关更多信息,请参见在 ASP.NET Core 中使用多个环境For more information, see 在 ASP.NET Core 中使用多个环境.

日志记录Logging

ASP.NET Core 支持适用于各种内置和第三方日志记录提供程序的日志记录 API。ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. 可用的提供程序包括:Available providers include the following:

  • 控制台Console
  • 调试Debug
  • Windows 事件跟踪Event Tracing on Windows
  • Windows 事件日志Windows Event Log
  • TraceSourceTraceSource
  • Azure 应用服务Azure App Service
  • Azure Application InsightsAzure Application Insights

通过从 DI 获取 ILogger 对象并调用日志方法,从应用代码中的任何位置写入日志。Write logs from anywhere in an app's code by getting an ILogger object from DI and calling log methods.

下面是使用 ILogger 对象的示例代码,其中突出显示了构造函数注入和日志记录方法调用。Here's sample code that uses an ILogger object, with constructor injection and the logging method calls highlighted.

public class TodoController : ControllerBase
{
    private readonly ILogger _logger;

    public TodoController(ILogger<TodoController> logger)
    {
        _logger = logger;
    }

    [HttpGet("{id}", Name = "GetTodo")]
    public ActionResult<TodoItem> GetById(string id)
    {
        _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
        // Item lookup code removed.
        if (item == null)
        {
            _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
            return NotFound();
        }
        return item;
    }
}

通过 ILogger 接口,可将任意数量的字段传递给日志提供程序。The ILogger interface lets you pass any number of fields to the logging provider. 字段通常用于构造消息字符串,但提供程序还可将其作为单独的字段发送到数据存储。The fields are commonly used to construct a message string, but the provider can also send them as separate fields to a data store. 此功能使日志提供程序可以实现语义日志记录,也称为结构化日志记录This feature makes it possible for logging providers to implement semantic logging, also known as structured logging.

有关更多信息,请参见ASP.NET Core 中的日志记录For more information, see ASP.NET Core 中的日志记录.

路由Routing

路由是映射到处理程序的 URL 模式。A route is a URL pattern that is mapped to a handler. 处理程序通常是 Razor 页面、MVC 控制器中的操作方法或中间件。The handler is typically a Razor page, an action method in an MVC controller, or a middleware. 借助 ASP.NET Core 路由,可以控制应用使用的 URL。ASP.NET Core routing gives you control over the URLs used by your app.

有关更多信息,请参见ASP.NET Core 中的路由For more information, see ASP.NET Core 中的路由.

错误处理Error handling

ASP.NET Core 具有用于处理错误的内置功能,例如:ASP.NET Core has built-in features for handling errors, such as:

  • 开发人员异常页A developer exception page
  • 自定义错误页Custom error pages
  • 静态状态代码页Static status code pages
  • 启动异常处理Startup exception handling

有关更多信息,请参见处理 ASP.NET Core 中的错误For more information, see 处理 ASP.NET Core 中的错误.

发出 HTTP 请求Make HTTP requests

IHttpClientFactory 的实现可用于创建 HttpClient 实例。An implementation of IHttpClientFactory is available for creating HttpClient instances. 工厂可以:The factory:

  • 提供一个中心位置,用于命名和配置逻辑 HttpClient 实例。Provides a central location for naming and configuring logical HttpClient instances. 例如,可以注册 github 客户端,并将它配置为访问 GitHub。For example, a github client can be registered and configured to access GitHub. 可以注册一个默认客户端用于其他用途。A default client can be registered for other purposes.
  • 支持多个委托处理程序的注册和链接,以生成出站请求中间件管道。Supports registration and chaining of multiple delegating handlers to build an outgoing request middleware pipeline. 此模式类似于 ASP.NET Core 中的入站中间件管道。This pattern is similar to the inbound middleware pipeline in ASP.NET Core. 此模式提供了一种用于管理围绕 HTTP 请求的横切关注点的机制,包括缓存、错误处理、序列化以及日志记录。The pattern provides a mechanism to manage cross-cutting concerns around HTTP requests, including caching, error handling, serialization, and logging.
  • 与 Polly 集成,这是用于瞬时故障处理的常用第三方库。Integrates with Polly, a popular third-party library for transient fault handling.
  • 管理基础 HttpClientMessageHandler 实例的池和生存期,避免在手动管理 HttpClient 生存期时出现常见的 DNS 问题。Manages the pooling and lifetime of underlying HttpClientMessageHandler instances to avoid common DNS problems that occur when manually managing HttpClient lifetimes.
  • (通过 ILogger)添加可配置的记录体验,以处理工厂创建的客户端发送的所有请求。Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

有关更多信息,请参见在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求For more information, see 在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求.

内容根Content root

内容根是应用所使用的任何专用内容的基路径,例如 Razor 文件。The content root is the base path to any private content used by the app, such as its Razor files. 默认情况下,内容根是托管应用的可执行文件的基路径。By default, the content root is the base path for the executable hosting the app. 构建主机时,可以指定备用位置。An alternative location can be specified when building the host.

有关详细信息,请参阅内容根For more information, see Content root.

有关详细信息,请参阅内容根For more information, see Content root.

Web 根Web root

Web 根(也称为 webroot)是公共、静态资源(例如 CSS、JavaScript 和图像文件)的基路径。The web root (also known as webroot) is the base path to public, static resources, such as CSS, JavaScript, and image files. 默认情况下,静态文件中间件仅提供来自 Web 根目录(及子目录)的文件。The static files middleware will only serve files from the web root directory (and sub-directories) by default. Web 根路径默认为 {Content Root}/wwwroot,但构建主机时可以指定其他位置。The web root path defaults to {Content Root}/wwwroot, but a different location can be specified when building the host.

在 Razor (.cshtml) 文件中,波浪号斜杠 ~/ 指向 Web 根。In Razor (.cshtml) files, the tilde-slash ~/ points to the web root. ~/ 开头的路径称为虚拟路径。Paths beginning with ~/ are referred to as virtual paths.

有关更多信息,请参见ASP.NET Core 中的静态文件For more information, see ASP.NET Core 中的静态文件.