ASP.NET Core in Action 2 Understanding ASP.NET Core

Part 1 Getting started with minimal APIs

第 1 部分:开始使用最少的 API

Web applications are everywhere these days, from social media web apps and news sites to the apps on your phone. Behind the scenes, there's almost always a server running a web application or an HTTP API. Web applications are expected to be infinitely scalable, deployed to the cloud, and highly performant. Getting started can be overwhelming at the best of times, and doing so with such high expectations can be even more of a challenge.

如今,Web 应用程序无处不在,从社交媒体 Web 应用程序和新闻网站到手机上的应用程序。在幕后,几乎总是有服务器运行 Web 应用程序或 HTTP API。Web 应用程序应具有无限可扩展性、部署到云中和高性能。在最好的情况下,开始可能会让人不知所措,而带着如此高的期望这样做可能是一个更大的挑战。

The good news for you as a reader is that ASP.NET Core was designed to meet those requirements. Whether you need a simple website, a complex e-commerce web app, or a distributed web of microservices, you can use your knowledge of ASP.NET Core to build lean web apps that fit your needs. ASP.NET Core lets you build and run web apps in Windows, Linux, or macOS. It's highly modular, so you use only the components you need, keeping your app as compact and performant as possible.

对于读者来说,好消息是 ASP.NET Core 旨在满足这些要求。无论您需要简单的网站、复杂的电子商务 Web 应用程序还是微服务的分布式 Web,您都可以利用自己的 ASP.NET Core 知识来构建符合您需求的精益 Web 应用程序。ASP.NET Core 允许您在 Windows、Linux 或 macOS 中构建和运行 Web 应用程序。它是高度模块化的,因此您只需使用所需的组件,从而使您的应用程序尽可能紧凑和高性能。

In part 1 you'll go from a standing start all the way to building your first API applications. Chapter 2 gives you a high-level overview of ASP.NET Core, which you'll find especially useful if you're new to web development in general. You'll get your first glimpse of a full ASP.NET Core application in chapter 3; we'll look at each component of the app in turn and see how they work together to generate a response.

在第 1 部分中,您将从零开始一直到构建您的第一个 API 应用程序。第 2 章为您提供了 ASP.NET Core 的高级概述,如果您一般是 Web 开发的新手,您会发现它特别有用。在第 3 章中,您将首次了解完整的 ASP.NET Core 应用程序;我们将看看app 中,并查看它们如何协同工作以生成响应。

Chapter 4 looks in detail at the middleware pipeline, which defines how incoming web requests are processed and how a response is generated. We'll look at several standard pieces of middleware and see how they can be combined to create your application's pipeline.

第 4 章详细介绍了中间件管道,它定义了如何处理传入的 Web 请求以及如何生成响应。我们将介绍几个标准的中间件,并了解如何将它们组合起来创建应用程序的管道。

Chapters 5 through 7 focus on building ASP.NET Core apps with minimal API endpoints, which are the new simplified approach to building JSON APIs in ASP.NET Core apps. In chapter 5 you'll learn how to create endpoints that generate JSON, how to use filters to extract common behavior, and how to use route groups to organize your APIs. In chapter 6 you'll learn about routing, the process of mapping URLs to endpoints. And in chapter 7 you'll learn about model binding and validation.

第 5 章到第 7 章重点介绍如何构建具有最少 API 端点的 ASP.NET Core 应用程序,这是在 ASP.NET Core 应用程序中构建 JSON API 的新简化方法。在第 5 章中,您将学习如何创建生成 JSON 的终端节点,如何使用过滤器提取常见行为,以及如何使用路由组来组织 API。在第 6 章中,您将了解路由,即将 URL 映射到端点的过程。在第 7 章中,您将学习模型绑定和验证。

There's a lot of content in part 1, but by the end you'll be well on your way to building simple APIs with ASP.NET Core. Inevitably, I'll gloss over some of the more complex configuration aspects of the framework, but you should get a good understanding of minimal APIs and how you can use them to build simple APIs. In later parts of this book, you'll learn how to configure your application and add extra features, such as user profiles and database interaction.

第 1 部分内容丰富,但到最后,您将顺利使用 ASP.NET Core 构建简单的 API。不可避免地,我将略过框架的一些更复杂的配置方面,但您应该很好地了解最小的 API 以及如何使用它们来构建简单的 API。在本书的后面部分,您将学习如何配置应用程序并添加额外的功能,例如用户配置文件和数据库交互。

We'll also look at how to build other types of applications, such as server-rendered web apps with Razor Pages.

我们还将了解如何构建其他类型的应用程序,例如使用 Razor Pages 构建服务器渲染的 Web 应用程序。

2 Understanding ASP.NET Core

2 了解 ASP.NET Core

This chapter covers

本章涵盖

  • Why ASP.NET Core was created
    创建 ASP.NET Core 的原因

  • The many application paradigms of ASP.NET Core Approaches to migrating an existing application to ASP.NET Core
    ASP.NET Core 的许多应用程序范例将现有应用程序迁移到 ASP.NET Core 的方法

In this chapter, I provide some background on ASP.NET Core: why web frameworks are useful, why ASP.NET Core was created, and how to choose when to use ASP.NET Core. If you’re new to .NET development, this chapter will help you understand the .NET landscape. If you’re already a .NET developer, I provide guidance on whether now is the right time to consider moving your focus to .NET Core and .NET 7, as well as on the advantages ASP.NET Core can offer over previous versions of ASP.NET.

在本章中,我将提供有关 ASP.NET Core 的一些背景知识:为什么 Web 框架很有用,为什么创建 ASP.NET Core,以及如何选择何时使用 ASP.NET Core。如果您不熟悉 .NET 开发,本章将帮助您了解 .NET 的前景。如果您已经是 .NET 开发人员,我将提供指导,说明现在是否是考虑将重点转移到 .NET Core 和 .NET 7 的合适时机,以及 ASP.NET Core 相对于以前版本的 ASP.NET 可以提供的优势。

2.1 Using a web framework‌

2.1 使用 Web 框架

If you’re new to web development, it can be daunting to move into an area with so many buzzwords and a plethora of ever-changing products. You may be wondering whether all those products are necessary. How hard can it be to return a file from a server?

如果您是 Web 开发的新手,那么进入一个拥有如此多流行语和大量不断变化的产品的领域可能会令人生畏。您可能想知道所有这些产品是否都是必要的。从服务器返回文件有多难?

Well, it’s perfectly possible to build a static web application without the use of a web framework, but its capabilities will be limited. As soon as you want to provide any kind of security or dynamism, you’ll likely run into difficulties, and the original simplicity that enticed you will fade before your eyes.

嗯,完全可以在不使用 Web 框架的情况下构建静态 Web 应用程序,但它的功能将受到限制。一旦你想提供任何类型的安全或活力,你可能会遇到困难,最初吸引你的简单性会在你眼前消失。

Just as desktop or mobile development frameworks can help you build native applications, ASP.NET Core makes writing web applications faster, easier, and more secure than trying to build everything from scratch. It contains libraries for common things like

正如桌面或移动开发框架可以帮助您构建原生应用程序一样,ASP.NET Core 使编写 Web 应用程序比尝试从头开始构建所有内容更快、更轻松、更安全。它包含用于常见内容的库,例如

  • Creating dynamically changing web pages Letting users log in to your web app
    创建动态变化的网页 允许用户登录到您的 Web 应用程序

  • Letting users use their Facebook accounts to log in to your web app
    允许用户使用其 Facebook 帐户登录您的 Web 应用程序

  • Providing a common structure for building maintainable applications
    为构建可维护的应用程序提供通用结构

  • Reading configuration files Serving image files
    读取配置文件提供图像文件

  • Logging requests made to your web app
    记录对 Web 应用程序发出的请求

The key to any modern web application is the ability to generate dynamic web pages. A dynamic web page may display different data depending on the current logged-in user, or it could display content submitted by users. Without a dynamic framework, it wouldn’t be possible to log in to websites or to display any sort of personalized data on a page. In short, websites like Amazon, eBay, and Stack

任何现代 Web 应用程序的关键是生成动态网页的能力。动态网页可能会根据当前登录的用户显示不同的数据,也可以显示用户提交的内容。如果没有动态框架,就不可能登录网站或在页面上显示任何类型的个性化数据。简而言之,Amazon、eBay 和 Stack 等网站

Overflow (shown in figure 2.1) wouldn’t be possible. Web frameworks for creating dynamic web pages are almost as old as the web itself, and Microsoft has created several over the years, so why create a new one?

溢出(如图 2.1 所示)是不可能的。用于创建动态网页的 Web 框架几乎与 Web 本身一样古老,Microsoft 多年来已经创建了多个框架,那么为什么要创建一个新的框架呢?

alt text

Figure 2.1 The Stack Overflow website (https://stackoverflow.com) is built with ASP.NET and has almost entirely dynamic content.

图 2.1 Stack Overflow 网站 (https://stackoverflow.com) 是使用 ASP.NET 构建的,几乎完全具有动态内容。

2.2 Why ASP.NET Core was created‌

2.2 创建 ASP.NET Core 的原因

Microsoft’s development of ASP.NET Core was motivated by the desire to create a web framework with five main goals:

Microsoft 开发 ASP.NET Core 的动机是希望创建一个具有五个主要目标的 Web 框架:

  • To be run and developed cross-platform
    跨平台运行和开发

  • To have a modular architecture for easier maintenance
    采用模块化架构,更易于维护

  • To be developed completely as open-source software
    完全作为开源软件开发

  • To adhere to web standards
    遵守 Web 标准

  • To be applicable to current trends in web development, such as client-side applications and deployment to cloud environments
    适用于 Web 开发的当前趋势,例如客户端应用程序和部署到云环境

To achieve all these goals, Microsoft needed a platform that could provide underlying libraries for creating basic objects such as lists and dictionaries, and for performing tasks such as simple file operations. Up to this point, ASP.NET development had always been focused—and dependent—on the Windows-only .NET Framework. For ASP.NET Core, Microsoft created a lightweight platform that runs on Windows, Linux, and macOS called .NET Core (subsequently .NET), as shown in figure 2.2.

为了实现所有这些目标,Microsoft 需要一个平台,该平台可以提供基础库,用于创建基本对象(如列表和字典)以及执行任务(如简单的文件作)。在此之前,ASP.NET 开发始终以仅限 Windows 的 .NET Framework 为中心。对于 ASP.NET Core,Microsoft创建了一个在 Windows、Linux 和 macOS 上运行的轻量级平台,称为 .NET Core(随后.NET),如图 2.2 所示。

alt text

Figure 2.2 The relationships among ASP.NET Core, ASP.NET, .NET Core/.NET 5+, and .NET Framework. ASP.NET Core runs on .NET Core and .NET 5+, so it can run cross-platform. Conversely, ASP.NET runs on .NET Framework only, so it’s tied to the Windows OS.

图 2.2 ASP.NET Core、ASP.NET、.NET Core/.NET 5+ 和 .NET Framework 之间的关系。ASP.NET Core 在 .NET Core 和 .NET 5+ 上运行,因此可以跨平台运行。相反,ASP.NET 仅在 .NET Framework 上运行,因此它与 Windows作系统相关联。

DEFINITION .NET 5 was the next version of .NET Core after 3.1, followed by .NET 6 and .NET 7. It represents a unification of .NET Core and other .NET platforms in a single runtime and framework. It was considered to be the future of .NET.
定义 .NET 5 是 3.1 之后的 .NET Core 的下一个版本,其次是 .NET 6 和 .NET 7。它表示 .NET Core 和其他 .NET 平台在单个运行时和框架中的统一。它被认为是 .NET 的未来。

which is why Microsoft chose to drop the “Core” from its name. For consistency with Microsoft’s language, I use the term .NET 5+ to refer to .NET 5, .NET 6, and .NET 7, and the term .NET Core to refer to previous versions.‌

这就是 Microsoft 选择从其名称中删除“Core”的原因。为了与 Microsoft 的语言保持一致,我使用术语 .NET 5+ 来指代 .NET 5、.NET 6 和 .NET 7,使用术语 .NET Core 来指代以前的版本。

.NET Core (and its successor, .NET 5+) employs many of the same APIs as .NET Framework but is more modular. It implements a different set of features from those in .NET Framework, with the goal of providing a simpler programming model and modern APIs. It’s a separate platform rather than a fork of .NET Framework, though it uses similar code for many of its APIs.

.NET Core(及其后续产品 .NET 5+)采用许多与 .NET Framework 相同的 API,但模块化程度更高。它实现了一组与 .NET Framework 中的功能不同的功能,目的是提供更简单的编程模型和现代 API。它是一个单独的平台,而不是 .NET Framework 的分支,尽管它的许多 API 都使用类似的代码。

NOTE If you’d like to learn more about the .NET ecosystem, you can read two posts on my blog: “Understanding the .NET ecosystem: The evolution of .NET into .NET 7” (http://mng.bz/Ao0W) and “Understanding the .NET ecosystem: The introduction of .NET Standard” (http://mng.bz/ZqPZ).
注意 如果您想了解有关 .NET 生态系统的更多信息,可以阅读我博客上的两篇文章:“了解 .NET 生态系统:.NET 向 .NET 7 的演变”(http://mng.bz/Ao0W 页)和“了解 .NET 生态系统:.NET Standard 简介”(http://mng.bz/ZqPZ 页)。

The benefits and limitations of ASP.NET
ASP.NET 的好处和局限性
ASP.NET Core is the latest evolution of Microsoft’s popular ASP.NET web framework, released in June 2016. Previous versions of ASP.NET had many incremental updates, focusing on high developer productivity and prioritizing backward compatibility. ASP.NET Core bucks that trend by making significant architectural changes that rethink the way the web framework is designed and built.
ASP.NET Core 是 Microsoft 流行的 ASP.NET Web 框架的最新发展版本,于 2016 年 6 月发布。以前的 ASP.NET 版本有许多增量更新,侧重于提高开发人员的工作效率并优先考虑向后兼容性。ASP.NET Core 通过对架构进行重大更改来重新思考 Web 框架的设计和构建方式,从而逆势而上。
ASP.NET Core owes a lot to its ASP.NET heritage, and many features have been carried forward from before, but ASP.NET Core is a new framework.
ASP.NET Core 在很大程度上归功于其 ASP.NET 传统,并且许多功能都从以前继承了下来,但 ASP.NET Core 是一个新框架。
The whole technology stack has been rewritten, including both the web framework and the underlying platform.
整个技术堆栈已被重写,包括 Web 框架和底层平台。
At the heart of the changes is the philosophy that ASP.NET should be able to hold its head high when measured against other modern frameworks, but existing .NET developers should continue to have a sense of familiarity.
这些变化的核心理念是这样一种理念,即 ASP.NET 与其他现代框架相比时,应该能够昂首挺胸,但现有的 .NET 开发人员应该继续保持熟悉感。
To understand why Microsoft decided to build a new framework, it’s important to understand the benefits and limitations of the legacy ASP.NET web framework.
要了解 Microsoft 决定构建新框架的原因,了解旧版 ASP.NET Web 框架的优势和局限性非常重要。
The first version of ASP.NET was released in 2002 as part of .NET Framework 1.0. The ASP.NET Web Forms paradigm that it introduced differed significantly from the conventional scripting environments of classic ASP and PHP. ASP.NET Web Forms allowed developers to create web applications rapidly by using a graphical designer and a simple event model that mirrored desktop application-building techniques.
ASP.NET 的第一个版本于 2002 年作为 .NET Framework 1.0的一部分发布. 它引入的 ASP.NET Web Forms 范例与传统 ASP 和 PHP 的传统脚本环境有很大不同。ASP.NET Web 窗体允许开发人员使用图形设计器和反映桌面应用程序构建技术的简单事件模型快速创建 Web 应用程序。
The ASP.NET framework allowed developers to create new applications quickly, but over time the web development ecosystem changed. It became apparent that ASP.NET Web Forms suffered from many problems, especially in building larger applications. In particular, a lack of testability, a complex stateful model, and limited influence on the generated HTML (making client- side development difficult) led developers to evaluate other options.
ASP.NET 框架允许开发人员快速创建新的应用程序,但随着时间的推移,Web 开发生态系统发生了变化。很明显,ASP.NET Web Forms 存在许多问题,尤其是在构建大型应用程序时。特别是,缺乏可测试性、复杂的有状态模型以及对生成的 HTML 的有限影响(使客户端开发变得困难)导致开发人员评估其他选项。
In response, Microsoft released the first version of ASP.NET MVC in 2009, based on the Model-View-Controller (MVC) pattern, a common web pattern used in frameworks such as Ruby on Rails, Django, and Java Spring. This framework allowed developers to separate UI elements from application logic, made testing easier, and provided tighter control of the HTML- generation process.
作为回应,Microsoft 于 2009 年发布了 ASP.NET MVC 的第一个版本,该版本基于模型-视图-控制器 (MVC) 模式,这是 Ruby on Rails、Django 和 Java Spring 等框架中使用的一种常见 Web 模式。该框架允许开发人员将 UI 元素与应用程序逻辑分离,使测试更容易,并提供对 HTML 生成过程的更严格控制。
ASP.NET MVC has been through four more iterations since its first release, but all these iterations were built on the same underlying framework provided by the System .Web.dll file. This library is part of .NET Framework, so it comes preinstalled with all versions of Windows. It contains all the core code that ASP.NET uses when you build a web application.
ASP.NET MVC 自首次发布以来已经经历了四次迭代,但所有这些迭代都是建立在 System 提供的相同底层框架之上的。Web.dll 文件。此库是 .NET Framework 的一部分,因此它预装在所有版本的 Windows 中。它包含 ASP.NET 在构建 Web 应用程序时使用的所有核心代码。
This dependency brings both advantages and disadvantages. On one hand, the ASP.NET framework is a reliable, battle-tested platform that’s fine for building web applications in Windows. It provides a wide range of features that have been in production for many years, and it’s well known by virtually all Windows web developers.
这种依赖关系既有优点也有缺点。一方面,ASP.NET 框架是一个可靠的、经过实战检验的平台,非常适合在 Windows 中构建 Web 应用程序。它提供了一系列已经投入生产多年的功能,几乎所有 Windows Web 开发人员都知道它。
On the other hand, this reliance is limiting. Changes to the underlying System.Web.dll file are far-reaching and, consequently, slow to roll out, which limits the extent to which ASP.NET is free to evolve and results in release cycles happening only every few years. There’s also an explicit coupling with the Windows web host, Internet Information Services (IIS), which precludes its use on non-Windows platforms.
另一方面,这种依赖是有限的。对基础 System.Web.dll 文件的更改影响深远,因此推出速度很慢,这限制了 ASP.NET 自由发展的程度,并导致发布周期每隔几年才发生一次。此外,还与 Windows Web 主机 Internet Information Services (IIS) 显式耦合,这阻止了它在非 Windows 平台上的使用。
More recently, Microsoft declared .NET Framework to be “done.” It won’t be removed or replaced, but it also won’t receive any new features.
最近,Microsoft 宣布 .NET Framework 已“完成”。它不会被删除或替换,但它也不会获得任何新功能。
Consequently, ASP.NET based on System.Web.dll won’t receive new features or updates either.
因此,基于 System.Web.dll 的 ASP.NET 也不会收到新功能或更新。
In recent years, many web developers have started looking at cross- platform web frameworks that can run on Windows as well as Linux and macOS. Microsoft felt the time had come to create a framework that was no longer tied to its Windows legacy; thus, ASP.NET Core was born.
近年来,许多 Web 开发人员开始寻找可以在 Windows 以及 Linux 和 macOS 上运行的跨平台 Web 框架。Microsoft 认为是时候创建一个不再与其 Windows 传统挂钩的框架了;因此,ASP.NET Core 诞生了。

With .NET 7, it’s possible to build console applications that run cross-platform. Microsoft created ASP.NET Core to be an additional layer on top of console applications so that converting to a web application involves adding and composing libraries, as shown in figure 2.3.

使用 .NET 7,可以构建跨平台运行的控制台应用程序。Microsoft Core 创建了 ASP.NET Core 作为控制台应用程序之上的附加层,因此转换为 Web 应用程序涉及添加和组合库,如图 2.3 所示。

alt text

Figure 2.3 ASP.NET Core application model. The .NET 7 platform provides a base console application model for running command-line apps. Adding a web server library converts this model to an ASP.NET Core web app. You can add other features, such as configuration and logging, using various libraries.

图 2.3 ASP.NET 核心应用程序模型。.NET 7 平台提供了用于运行命令行应用程序的基本控制台应用程序模型。添加 Web 服务器库会将此模型转换为 ASP.NET Core Web 应用程序。您可以使用各种库添加其他功能,例如配置和日志记录。

When you add an ASP.NET Core web server to your .NET 7 app, your console application can run as a web application.

将 ASP.NET Core Web 服务器添加到 .NET 7 应用时,控制台应用程序可以作为 Web 应用程序运行。

ASP.NET Core contains a huge number of APIs, but you’ll rarely need all the features available to you. Some of the features are built in and will appear in virtually every application you create, such as the ones for reading configuration files or performing logging. Other features are provided by separate libraries and built on top of these base capabilities to provide application-specific functionality, such as third-party logins via Facebook or Google.

ASP.NET Core 包含大量 API,但您很少需要所有可用的功能。某些功能是内置的,几乎会出现在您创建的每个应用程序中,例如用于读取配置文件或执行日志记录的应用程序。其他功能由单独的库提供,并基于这些基本功能构建,以提供特定于应用程序的功能,例如通过 Facebook 或 Google 进行第三方登录。

Most of the libraries and APIs you’ll use in ASP.NET Core are available on GitHub, in the Microsoft .NET organization repositories at https://github.com/dotnet/aspnetcore. You can find the core APIs there, including the authentication and logging APIs, as well as many peripheral libraries, such as the third-party authentication libraries.

您将在 ASP.NET Core 中使用的大多数库和 API 都可以在 GitHub 的 Microsoft .NET 组织存储库中找到 https://github.com/dotnet/aspnetcore。您可以在其中找到核心 API,包括身份验证和日志记录 API,以及许多外围库,例如第三方身份验证库。

All ASP.NET Core applications follow a similar design for basic configuration, but in general the framework is flexible, leaving you free to create your own code conventions. These common APIs, the extension libraries that build on them, and the design conventions they promote are covered by the somewhat-nebulous term ASP.NET Core.

所有 ASP.NET Core 应用程序都遵循类似的基本配置设计,但总的来说,该框架是灵活的,让您可以自由创建自己的代码约定。这些常见的 API、基于它们的扩展库以及它们所促进的设计约定都包含在有点模糊的术语 ASP.NET Core 中。

2.3 Understanding the many paradigms of ASP.NET Core‌

2.3 了解 ASP.NET Core 的多种范式

In chapter 1 you learned that ASP.NET Core provides a generalized web framework that can be used to build a wide variety of applications. As you may recall from section 1.2, the main paradigms are

在第 1 章中,您了解了 ASP.NET Core 提供了一个通用的 Web 框架,可用于构建各种应用程序。你可能还记得 1.2 节,主要的范例是

  • Minimal APIs—Simple HTTP APIs that can be consumed by mobile applications or browser-based single-page applications (SPAs)
    最少的 API — 可由移动应用程序或基于浏览器的单页应用程序 (SPA) 使用的简单 HTTP API

  • Web APIs—An alternative approach for building HTTP APIs that adds more structure and features than minimal APIs
    Web API — 一种构建 HTTP API 的替代方法,与最少的 API 相比,它增加了更多的结构和功能

  • gRPC APIs—Used to build efficient binary APIs for server-to-server communication using the gRPC protocol
    gRPC API — 用于使用 gRPC 协议构建高效的二进制 API,以实现服务器到服务器的通信

  • Razor Pages—Used to build page-based server- rendered applications
    Razor Pages - 用于构建基于页面的服务器渲染的应用程序

  • MVC controllers—Similar to Razor Pages; used for server-based applications but without the page- based paradigm
    MVC 控制器 — 类似于 Razor Pages;用于基于服务器的应用程序,但没有基于页面的范例

  • Blazor WebAssembly—A browser-based SPA framework using the WebAssembly standard, similar to JavaScript frameworks such as Angular, React, and Vue
    Blazor WebAssembly - 使用 WebAssembly 标准的基于浏览器的 SPA 框架,类似于 Angular、React 和 Vue 等 JavaScript 框架

  • Blazor Server—Used to build stateful applications, rendered on the server, that send UI events and page updates over WebSockets to provide the feel of a client-side SPA but with the ease of development of a server-rendered application
    Blazor Server - 用于构建在服务器上呈现的有状态应用程序,这些应用程序通过 WebSockets 发送 UI 事件和页面更新,以提供客户端 SPA 的感觉,但易于开发服务器呈现的应用程序

All these paradigms use the core functionality of ASP.NET Core and layer the additional functionality on top. Each paradigm is suited to a different style of web application or API, so some may fit better than others, depending on what sort of application you’re building.

所有这些范例都使用 ASP.NET Core 的核心功能,并将附加功能分层。每种范例都适合不同风格的 Web 应用程序或 API,因此有些可能比其他范例更适合,具体取决于您正在构建的应用程序类型。

Traditional page-based, server-side-rendered web applications are the bread and butter of ASP.NET development, both in the previous version of ASP.NET and now in ASP.NET Core. The Razor Pages and MVC controller paradigms provide two slightly different styles for building these types of applications but have many of the same concepts, as you’ll see in part 2. These paradigms can be useful for building rich, dynamic websites, whether they’re e- commerce sites, content management systems (CMSes), or large n-tier applications. Both the open-source CMS Orchard Core1 (figure 2.4) and cloudscribe2 CMS project, for example, are built with ASP.NET Core.

传统的基于页面、服务器端呈现的 Web 应用程序是 ASP.NET 开发的基础,无论是在以前的 ASP.NET 版本中,还是在现在的 ASP.NET Core 中。Razor Pages 和 MVC 控制器范例为构建这些类型的应用程序提供了两种略有不同的样式,但具有许多相同的概念,您将在第 2 部分中看到。这些范例可用于构建丰富的动态网站,无论它们是电子商务网站、内容管理系统 (CMS) 还是大型 n 层应用程序。例如,开源 CMS Orchard Core1(图 2.4)和 cloudscribe2 CMS 项目都是使用 ASP.NET Core 构建的。

alt text

Figure 2.4 The California School Information Services website (https://csis.fcmat.org) is built with Orchard Core and ASP.NET Core.

图 2.4 California School Information Services 网站 (https://csis.fcmat.org) 是使用 Orchard Core 和 ASP.NET Core 构建的。

In addition to server-rendered applications, ASP.NET core is ideally suited to building a REST or HTTP API server. Whether you’re building a mobile app, a JavaScript SPA using Angular, React, Vue, or some other client-side framework, it’s easy to create an ASP.NET Core application to act as the server-side API by using both the minimal API and web API paradigms built into ASP.NET Core. You’ll learn about minimal APIs in part 1 and about web APIs in chapter 20.

除了服务器渲染的应用程序外,ASP.NET 核心还非常适合构建 REST 或 HTTP API 服务器。无论您是使用 Angular、React、Vue 还是其他客户端框架构建移动应用程序、JavaScript SPA,都可以通过使用 ASP.NET Core 中内置的最小 API 和 Web API 范例轻松创建 ASP.NET Core 应用程序以充当服务器端 API。您将在第 1 部分中了解最小 API,在第 20 章中了解 Web API。

DEFINITION REST stands for representational state transfer. RESTful applications typically use lightweight and stateless HTTP calls to read, post (create/ update), and delete data.

定义 REST 代表 representational state transfer。RESTful 应用程序通常使用轻量级和无状态的 HTTP 调用来读取、发布(创建/更新)和删除数据。

ASP.NET Core isn’t restricted to creating RESTful services. It’s easy to create a web service or remote procedure call (RPC)- style service for your application, using gRPC for example, as shown in figure 2.5. In the simplest case, your application might expose only a single endpoint! ASP.NET Core is perfectly designed for building simple services, thanks to its cross-platform support and lightweight design.

ASP.NET Core 并不局限于创建 RESTful 服务。为您的应用程序创建 Web 服务或远程过程调用 (RPC) 样式的服务很容易,例如使用 gRPC,如图 2.5 所示。在最简单的情况下,您的应用程序可能只公开一个端点!ASP.NET Core 具有跨平台支持和轻量级设计,专为构建简单服务而设计。

DEFINITION gRPC is a modern open-source, high- performance RPC framework. You can read more at https://grpc.io.

定义 gRPC 是一个现代的开源、高性能 RPC 框架。您可以在 https://grpc.io 上阅读更多内容。

alt text
alt text

Figure 2.5 ASP.NET Core can act as the server-side application for a variety of clients: it can serve HTML pages for traditional web applications, act as a REST API for client-side SPA applications, or act as an ad hoc RPC service for client applications.

图 2.5 ASP.NET Core 可以充当各种客户端的服务器端应用程序:它可以为传统 Web 应用程序提供 HTML 页面,充当客户端 SPA 应用程序的 REST API,或充当客户端应用程序的临时 RPC 服务。

As well as server-rendered web apps, APIs, and gRPC endpoints, ASP.NET Core includes the Blazor framework, which can be used to build two very different styles of application. Blazor WebAssembly (WASM) apps run directly in your browser, in the same way as traditional JavaScript SPA frameworks such as Angular and React. Your .NET code is compiled to WebAssembly (https://webassembly.org) or executes on a .NET runtime compiled for WASM, and the browser downloads and runs it as it would a JavaScript app.

除了服务器呈现的 Web 应用、API 和 gRPC 终结点外,ASP.NET Core 还包括 Blazor 框架,该框架可用于构建两种截然不同的应用程序样式。Blazor WebAssembly (WASM) 应用直接在浏览器中运行,其方式与传统的 JavaScript SPA 框架(如 Angular 和 React)相同。您的 .NET 代码被编译为 WebAssembly (https://webassembly.org) 或在为 WASM 编译的 .NET 运行时上执行,浏览器会像下载 JavaScript 应用程序一样下载和运行它。

This way you can build highly interactive client-side applications while using C# and all the .NET APIs and libraries you already know.

这样,您就可以在使用 C# 和您已经知道的所有 .NET API 和库的同时构建高度交互的客户端应用程序。

By contrast, Blazor Server applications run on the server. Each mouse click or keyboard event is sent to the server via WebSockets. Then the server calculates the changes that should be made to the UI and sends the required changes back to the client, which updates the page in the browser.

相比之下,Blazor Server 应用程序在服务器上运行。每个鼠标单击或键盘事件都通过 WebSockets 发送到服务器。然后,服务器计算应该对 UI 进行的更改,并将所需的更改发送回客户端,客户端会在浏览器中更新页面。

The result is a “stateful” application that runs server-side but can be used to build highly interactive SPAs. The main downside of Blazor Server is that it requires a constant internet connection.

结果是一个“有状态”应用程序,它在服务器端运行,但可用于构建高度交互的 SPA。Blazor Server 的主要缺点是它需要持续的 Internet 连接。

NOTE In this book I focus on building traditional page-based, server-side- rendered web applications and RESTful web APIs. I also show how to create background worker services in chapter 34. For more information on Blazor, I recommend Blazor in Action, by Chris Sainty (Manning, 2022).‌

注意 在这本书中,我重点介绍了如何构建传统的基于页面、服务器端渲染的 Web 应用程序和 RESTful Web API。我还在 Chapter 34 中展示了如何创建后台 worker 服务。有关 Blazor 的更多信息,我推荐 Chris Sainty 的 Blazor in Action(曼宁,2022 年)。

With the ability to call on all these paradigms, you can use ASP.NET Core to build a wide variety of applications, but it’s still worth considering whether ASP.NET Core is right for your specific application. That decision will likely be affected by both your experience with .NET and the application you want to build.
由于能够调用所有这些范式,您可以使用 ASP.NET Core 构建各种应用程序,但仍然值得考虑 ASP.NET Core 是否适合您特定应用。该决定可能会受到您对 .NET 的体验和要构建的应用程序的影响。

2.4 When to choose ASP.NET Core‌

2.4 何时选择 ASP.NET Core

In this section I’ll describe some of the points to consider when deciding whether to use ASP.NET Core and .NET 7 instead of legacy .NET Framework ASP.NET. In most cases the decision will be to use ASP.NET Core, but you should consider some important caveats.

在本节中,我将介绍在决定是否使用 ASP.NET Core 和 .NET 7 而不是旧版 .NET Framework ASP.NET 时要考虑的一些要点。在大多数情况下,您决定使用 ASP.NET Core,但您应该考虑一些重要的注意事项。

When choosing a platform, you should consider multiple factors, not all of which are technical. One such factor is the level of support you can expect to receive from its creators. For some organizations, limited support can be one of the main obstacles to adopting open-source software. Luckily, Microsoft has pledged to provide full support for Long Term Support (LTS) versions of .NET and ASP.NET Core for at least three years from the time of their release. And as all development takes place in the open, sometimes you can get answers to your questions from the general community as well as from Microsoft directly.

选择平台时,您应该考虑多个因素,并非所有因素都是技术因素。其中一个因素是您可以期望从其创建者那里获得的支持水平。对于某些组织来说,有限的支持可能是采用开源软件的主要障碍之一。幸运的是,Microsoft 已承诺为 .NET 和 ASP.NET Core 的长期支持 (LTS) 版本提供全面支持,从发布之日起至少三年。由于所有开发都是在公开环境中进行的,因此有时您可以从一般社区以及直接从 Microsoft 获得问题的答案。

NOTE You can view Microsoft’s official support policy at http://mng.bz/RxXP.

注意: 您可以在 http://mng.bz/RxXP 查看 Microsoft 的官方支持政策。

When deciding whether to use ASP.NET Core, you have two primary dimensions to consider: whether you’re already a .NET developer and whether you’re creating a new application or looking to convert an existing one.

在决定是否使用 ASP.NET Core 时,您需要考虑两个主要方面:您是否已经是.NET 开发人员,无论您是要创建新应用程序还是希望转换现有应用程序。

2.4.1 If you’re new to .NET development‌

2.4.1 如果您不熟悉 .NET 开发

If you’re new to .NET development, you’re joining at a great time! Many of the growing pains associated with a new framework have been worked out, and the result is a stable, high-performance, cross-platform application framework.

如果你是 .NET 开发的新手,那么加入的时机正好!与新框架相关的许多成长之痛已经解决,结果是一个稳定、高性能、跨平台的应用程序框架。

The primary language of .NET development, and of ASP.NET Core in particular, is C#. This language has a huge following, for good reason! As an object-oriented C-based language, it provides a sense of familiarity to those who are used to C, Java, and many other languages. In addition, it has many powerful features, such as Language Integrated Query (LINQ), closures, and asynchronous programming constructs. The C# language is also designed in the open on GitHub, as is Microsoft’s C# compiler, code-named Roslyn (https://github.com/dotnet/roslyn).

.NET 开发(尤其是 ASP.NET Core 的主要语言)是 C#。这种语言有大量的追随者,这是有充分理由的!作为一种面向对象的基于 C 语言,它为习惯了 C、Java 和许多其他语言的人提供了一种熟悉感。此外,它还具有许多强大的功能,例如语言集成查询 (LINQ)、闭包和异步编程结构。C# 语言也是在 GitHub 上公开设计的,Microsoft 的 C# 编译器,代号为 Roslyn (https://github.com/dotnet/roslyn)。

NOTE I use C# throughout this book and will highlight some of the newer features it provides, but I won’t be teaching the language from scratch. If you want to learn C#, I recommend C# in Depth, 4th ed., by Jon Skeet (Manning, 2019), and Code Like a Pro in C#, by Jort Rodenburg (Manning, 2021).‌‌‌

注意 我在本书中都使用了 C#,并将重点介绍它提供的一些新功能,但我不会从头开始教授这门语言。如果您想学习 C#,我推荐 Jon Skeet 的 C# in Depth,第 4 版(Manning,2019 年)和 Jort Rodenburg 的 Code Like a Pro in C#(Manning,2021 年)。

One big advantage of ASP.NET Core and .NET 7 over .NET Framework is that they enable you to develop and run on any platform. With .NET 7 you can build and run the same application on Mac, Windows, and Linux, and even deploy to the cloud using tiny container deployments.
与 .NET Framework 相比,ASP.NET Core 和 .NET 7 的一大优势是,它们使您能够在任何平台上进行开发和运行。使用 .NET 7,您可以构建和运行相同的Mac、Windows 和 Linux 上的应用程序,甚至可以使用微型容器部署部署到云中。

Built with containers in mind
以容器为构建理念
Traditionally, web applications were deployed directly to a server or, more recently, to a virtual machine. Virtual machines allow operating systems to be installed in a layer of virtual hardware, abstracting away the underlying hardware. This approach has several advantages over direct installation, such as easy maintenance, deployment, and recovery. Unfortunately, virtual machines are also heavy, in terms of both file size and resource use.
传统上,Web 应用程序直接部署到服务器,或者最近部署到虚拟机。虚拟机允许将作系统安装在虚拟硬件层中,从而抽象出底层硬件。与直接安装相比,此方法具有多个优点,例如易于维护、部署和恢复。遗憾的是,虚拟机在文件大小和资源使用方面也很繁重。
This is where containers come in. Containers are far more lightweight and don’t have the overhead of virtual machines. They’re built in a series of layers and don’t require you to boot a new operating system when starting a new one, so they’re quick to start and great for quick provisioning.Containers (Docker in particular) are quickly becoming the go-to platform for building large, scalable systems.
这就是容器的用武之地。容器的轻量级要轻得多,并且没有虚拟机的开销。它们构建在一系列层中,在启动新作系统时不需要启动新作系统,因此它们可以快速启动,非常适合快速配置。容器(尤其是 Docker)正迅速成为构建大型可扩展系统的首选平台。
Containers have never been a particularly attractive option for ASP.NET applications, but with ASP.NET Core, .NET 7, and Docker for Windows, all that is changing. A lightweight ASP.NET Core application running on the cross-platform .NET 7 framework is perfect for thin container deployments. You can learn more about your deployment options in chapter 27.
容器从来都不是 ASP.NET 应用程序特别有吸引力的选择,但随着 ASP.NET Core、.NET 7 和 Docker for Windows 的推出,这一切都发生了变化。在跨平台 .NET 7 框架上运行的轻量级 ASP.NET Core 应用程序非常适合瘦容器部署。您可以在第 27 章中了解有关部署选项的更多信息。

In addition to running on each platform, one of the selling points of .NET is your ability to write and compile only once. Your application is compiled to Intermediate Language (IL) code, which is a platform-independent format. If a target system has the .NET 7 runtime installed, you can run compiled IL from any platform. You can develop on a Mac or a Windows machine, for example, and deploy exactly the same files to your production Linux machines. This compile-once, run-anywhere promise has finally been realized with ASP.NET Core and .NET 7.
除了在每个平台上运行之外,.NET 的卖点之一是您能够只编写和编译一次。您的应用程序被编译为中间语言 (IL) 代码,这是一种与平台无关的格式。如果目标系统安装了 .NET 7 运行时,则可以从任何平台运行编译的 IL。例如,您可以在 Mac 或 Windows 计算机上进行开发,并将完全相同的文件部署到生产 Linux 计算机上。“一次编写,到处运行”的承诺终于在 ASP.NET Core 和 .NET 7 中实现了。

TIP You can go one step further and package the .NET runtime with your app in a so-called self-contained deployment (SCD). This way, you can deploy cross-platform, and the target machine doesn’t even need .NET installed.
With SCDs, the generated deployment files are customized for the target machine, so you’re no longer deploying the same files everywhere in this case.

提示 您可以更进一步,将 .NET 运行时与您的应用程序打包到所谓的自包含部署 (SCD) 中。这样,您可以跨平台部署,并且目标计算机甚至不需要安装 .NET。使用 SCD 时,生成的部署文件会针对目标计算机进行自定义,因此在这种情况下,您不再需要在任何地方部署相同的文件。

Many of the web frameworks available today use similar well-established design patterns, and ASP.NET Core is no different. Ruby on Rails, for example, is known for its use of the MVC pattern; Node.js is known for the way it processes requests using small discrete modules (called a pipeline); and dependency injection is available in a wide variety of frameworks. If these techniques are familiar to you, you should find it easy to transfer them to ASP.NET Core; if they’re new to you, you can look forward to using industry best practices!

当今可用的许多 Web 框架都使用类似的成熟设计模式,ASP.NET Core 也不例外。例如,Ruby on Rails 以其对 MVC 模式的使用而闻名;Node.js 以其使用小型离散模块(称为管道)处理请求的方式而闻名;依赖项注入可用于各种框架。如果您熟悉这些技术,您应该会发现将它们传输到 ASP.NET Core 很容易;如果您对他们不熟悉,您可以期待使用行业最佳实践!

NOTE Design patterns are solutions to common software design problems. You’ll encounter a pipeline in chapter 4, dependency injection in chapters 8 and 9, and MVC in chapter 19.

注意 设计模式是常见软件设计问题的解决方案。您将在第 4 章中遇到管道,在第 8 章和第 9 章中遇到依赖关系注入,在第 19 章中遇到 MVC。

Whether you’re new to web development generally or only with .NET, ASP.NET Core provides a rich set of features with which you can build applications but doesn’t overwhelm you with concepts, as the legacy ASP.NET framework did. On the other hand, if you’re familiar with .NET, it’s worth considering whether now is the time to take a look at ASP.NET Core.

无论你是一般的 Web 开发新手,还是只使用 .NET,ASP.NET Core 都提供了一组丰富的功能,你可以利用这些功能构建应用程序,但不会像旧版 ASP.NET 框架那样被概念所淹没。在另一方面,如果您熟悉 .NET,则值得考虑现在是否是了解 ASP.NET Core 的时候。

2.4.2 If you’re a .NET Framework developer creating a new application‌

2.4.2 如果您是创建新应用程序的 .NET Framework 开发人员

If you’re already a .NET Framework developer, you’ve likely been aware of .NET Core and ASP.NET Core, but perhaps you were wary about jumping in too soon or didn’t want to hit the inevitable “version 1” problems. The good news is that ASP.NET Core and .NET are now mature, stable platforms, and it’s absolutely time to consider using .NET 7 for your new apps.

如果您已经是 .NET Framework 开发人员,您可能已经了解 .NET Core 和 ASP.NET Core,但也许您担心过早加入,或者不想遇到不可避免的“版本 1”问题。好消息是,ASP.NET Core 和 .NET 现在是成熟、稳定的平台,绝对是时候考虑将 .NET 7 用于您的新应用程序了。

As a .NET developer, if you aren’t using any Windows-specific constructs such as the Registry, the ability to build and deploy cross-platform opens the possibility for cheaper Linux hosting in the cloud, or for developing natively in macOS without the need for a virtual machine.

作为 .NET 开发人员,如果您不使用任何特定于 Windows 的结构(如注册表),则构建和部署跨平台的能力为在云中托管 Linux 或无需虚拟机即可在 macOS 中进行本机开发提供了可能性。

.NET Core and .NET 7 are inherently cross-platform, but you can still use platform-specific features if you need to.Windows-specific features such as the Registry and Directory Services, for example, can be enabled with a Compatibility Pack that makes these APIs available in .NET 5+. They’re available only when running .NET 5+ in Windows, not Linux or macOS, so you need to take care that such applications run only in a Windows environment or account for the potential missing APIs.

.NET Core 和 .NET 7 本质上是跨平台的,但如果需要,你仍然可以使用特定于平台的功能。特定于 Windows 的功能(例如,注册表和目录服务)可以通过兼容包启用,使这些 API 在 .NET 5+ 中可用。它们仅在 Windows 中运行 .NET 5+ 时可用,而不是在 Linux 或 macOS 中运行,因此您需要注意此类应用程序仅在 Windows 环境中运行,或者考虑可能缺少的 API。

TIP The Windows Compatibility Pack is designed to help port code from .NET Framework to .NET Core/.NET 5+. See http://mng.bz/2DeX.

提示 Windows 兼容包旨在帮助将代码从 .NET Framework 移植到 .NET Core/.NET 5+。请参阅 http://mng.bz/2DeX

The hosting model for the previous ASP.NET framework was a relatively complex one, relying on Windows IIS to provide the web-server hosting. In a cross-platform environment, this kind of symbiotic relationship isn’t possible, so an alternative hosting model has been adopted—one that separates web applications from the underlying host. This opportunity has led to the development of Kestrel, a fast, cross-platform HTTP server on which ASP.NET Core can run.

以前的 ASP.NET 框架的托管模型相对复杂,依赖 Windows IIS 提供 Web 服务器托管。在跨平台环境中,这种共生关系是不可能的,因此采用了另一种托管模型,即将 Web 应用程序与底层主机分开的模型。这个机会导致了 Kestrel 的开发,这是一种快速、跨平台的 HTTP 服务器,ASP.NET Core 可以在该服务器上运行。

Instead of the previous design, whereby IIS calls into specific points of your application, ASP.NET Core applications are console applications that self-host a web server and handle requests directly, as shown in figure 2.6. This hosting model is conceptually much simpler and allows you to test and debug your applications from the command line, though it doesn’t necessarily remove the need to run IIS (or the equivalent) in production.

与以前的设计不同,IIS 调用应用程序的特定点,ASP.NET Core 应用程序是自托管 Web 服务器并直接处理请求的控制台应用程序,如图 2.6 所示。此托管模型在概念上要简单得多,并且允许您从命令行测试和调试应用程序,尽管它不一定消除在生产中运行 IIS(或等效项)的需要。

ASP.NET Core and reverse proxies
ASP.NET Core 和反向代理
You can expose ASP.NET Core applications directly to the internet so that Kestrel receives requests directly from the network. That approach is fully supported. It’s more common, however, to use a reverse proxy between the raw network and your application. In Windows, the reverse-proxy server typically is IIS; in Linux or macOS, it might be NGINX, HAProxy, or Apache.There’s even an ASP.NET Core-based reverse proxy library called YARP (https://microsoft.github.io/reverse-proxy) that you can use to build your own reverse proxy.
您可以将 ASP.NET Core 应用程序直接公开到 Internet,以便 Kestrel 直接从网络接收请求。这种方法完全受支持。但是,更常见的是在原始网络和应用程序之间使用反向代理。在 Windows 中,反向代理服务器通常是 IIS;在 Linux 或 macOS 中,它可能是 NGINX、HAProxy 或 Apache。甚至还有一个名为 YARP (https://microsoft.github.io/reverse-proxy) 的基于 ASP.NET Core 的反向代理库,您可以使用它来构建自己的反向代理。
A reverse proxy is software responsible for receiving requests and forwarding them to the appropriate web server. The reverse proxy is exposed directly to the internet, whereas the underlying web server is exposed only to the proxy. This setup has several benefits, primarily security and performance for the web servers.
反向代理是负责接收请求并将其转发到适当的 Web 服务器的软件。反向代理直接向 Internet 公开,而底层 Web 服务器仅向代理公开。此设置有几个好处,主要是 Web 服务器的安全性和性能。
You may think that having a reverse proxy and a web server is somewhat redundant. Why not have one or the other? Well, one benefit is the decoupling of your application from the underlying operating system. The same ASP.NET Core web server, Kestrel, can be cross-platform and used behind a variety of proxies without putting any constraints on a particular implementation. Alternatively, if you wrote a new ASP.NET Core web server, you could use it in place of Kestrel without needing to change anything else about your application.
您可能认为拥有反向代理和 Web 服务器有点多余。为什么不拥有一个或另一个呢?嗯,一个好处是将您的应用程序与底层作系统解耦。相同的 ASP.NET Core Web 服务器 Kestrel 可以是跨平台的,并在各种代理后面使用,而不会对特定实现施加任何限制。或者,如果您编写了一个新的 ASP.NET Core Web 服务器,则可以使用它来代替 Kestrel,而无需更改有关应用程序的任何其他内容。
Another benefit of a reverse proxy is that it can be hardened against potential threats from the public internet. Reverse proxies are often responsible for additional aspects, such as restarting a process that has crashed. Kestrel can remain a simple HTTP server, not having to worry about these extra features, when it’s used behind a reverse proxy. You can think of this approach as being a simple separation of concerns: Kestrel is concerned with generating HTTP responses, whereas the reverse proxy is concerned with handling the connection to the internet.
反向代理的另一个好处是它可以针对来自公共互联网的潜在威胁进行强化。反向代理通常负责其他方面,例如重新启动已崩溃的进程。Kestrel 可以保持一个简单的 HTTP 服务器,当它在反向代理后面使用时,不必担心这些额外的功能。您可以将此方法视为简单的关注点分离:Kestrel 关注生成 HTTP 响应,而反向代理关注处理与 Internet 的连接。

alt text
alt text

Figure 2.6 The difference between hosting models in ASP.NET (top) and ASP.NET Core (bottom). In the previous version of ASP.NET, IIS is tightly coupled with the application. The hosting model in ASP.NET Core is simpler; IIS hands off the request to a self-hosted web server in the ASP.NET Core application and receives the response but has no deeper knowledge of the application.

图 2.6 在 ASP.NET(上)和 ASP.NET Core 中托管模型(下)之间的区别。在早期版本的 ASP.NET 中,IIS 与应用程序紧密耦合。ASP.NET Core 中的托管模型更简单;IIS 将请求移交给 ASP.NET Core 应用程序中的自托管 Web 服务器并接收响应,但对应用程序没有更深入的了解。

NOTE By default, when running in Windows, ASP.NET Core runs inside IIS, as shown in figure 2.6, which can provide better performance than the reverse-proxy version. This is primarily a deployment detail and doesn’t change the way you build ASP.NET Core applications.

注意 默认情况下,在 Windows 中运行时,ASP.NET Core 在 IIS 中运行,如图 2.6 所示,它可以提供比反向代理版本更好的性能。这主要是部署详细信息,不会改变您构建 ASP.NET Core 应用程序的方式。

Changing the hosting model to use a built-in HTTP web server has created another opportunity. Performance has been something of a sore point for ASP.NET applications in the past. It’s certainly possible to build high-performing applications—Stack Overflow (https://stackoverflow.com) is a testament to that fact—but the web framework itself isn’t designed with performance as a priority, so it can end up being an obstacle.

将托管模型更改为使用内置 HTTP Web 服务器创造了另一个机会。过去,性能一直是 ASP.NET 应用程序的痛点。构建高性能应用程序当然是可能的 — Stack Overflow (https://stackoverflow.com) 证明了这一事实 — 但 Web 框架本身在设计时并未将性能作为优先事项,因此它最终可能会成为一个障碍。

To make the product competitive cross-platform, the ASP.NET team focused on making the Kestrel HTTP server as fast as possible. TechEmpower (https://www.techempower.com/benchmarks) has been running benchmarks on a wide range of web frameworks from various languages for several years now. In round 20 of the plain-text benchmarks, TechEmpower announced that ASP.NET Core with Kestrel was among the 10 fastest of more than 400 frameworks tested!3

为了使产品在跨平台方面具有竞争力,ASP.NET 团队专注于使 Kestrel HTTP 服务器尽可能快。TechEmpower (https://www.techempower.com/benchmarks) 多年来一直在各种语言的各种 Web 框架上运行基准测试。在第 20 轮纯文本基准测试中,TechEmpower 宣布 ASP.NET Core with Kestrel 是测试的 400 多个框架中最快的 10 个框架之一!3

Web servers: Naming things is hard
Web 服务器:命名很困难
One difficult aspect of programming for the web is the confusing array of often-conflicting terminology. If you’ve used IIS, for example, you may have described it as a web server or possibly a web host. Conversely, if you’ve ever built an application with Node.js, you may have also referred to that application as a web server. Or you may have called the physical machine on which your application runs a web server. Similarly, you may have built an application for the internet and called it a website or a web application, probably somewhat arbitrarily based on the level of dynamism it displayed.
Web 编程的一个困难方面是一系列经常相互冲突的令人困惑的术语。例如,如果您使用过 IIS,您可能已将其描述为 Web 服务器或可能是 Web 主机。相反,如果您曾经使用 Node.js 构建过应用程序,您可能也曾将该应用程序称为 Web 服务器。或者,您可能已将运行应用程序的物理计算机称为 Web 服务器。同样,您可能已经构建了一个用于 Internet 的应用程序,并将其称为网站或 Web 应用程序,可能根据它显示的动态水平有点武断。
In this book, when I say web server in the context of ASP.NET Core, I’m referring to the HTTP server that runs as part of your ASP.NET Core application. By default, this server is the Kestrel web server, but that’s not a requirement. It’s possible to write a replacement web server for Kestrel if you so desire.
在本书中,当我在 ASP.NET Core 的上下文中提到 Web 服务器时,我指的是作为 ASP.NET Core 应用程序的一部分运行的 HTTP 服务器。默认情况下,此服务器是 Kestrel Web 服务器,但这不是必需的。如果您愿意,可以为 Kestrel 编写替换 Web 服务器。
The web server is responsible for receiving HTTP requests and generating responses. In the previous version of ASP.NET, IIS took this role, but in ASP.NET Core, Kestrel is the web server.
Web 服务器负责接收 HTTP 请求并生成响应。在早期版本的 ASP.NET 中,IIS 承担了此角色,但在 ASP.NET Core 中,Kestrel 是 Web 服务器。
I’ll use the term web application in this book to describe ASP.NET Core applications, regardless of whether they contain only static content or are dynamic. Either way, these applications are accessed via the web, so that name seems to be the most appropriate.
在本书中,我将使用术语 Web 应用程序来描述 ASP.NET Core 应用程序,无论它们只包含静态内容还是动态的。无论哪种方式,这些应用程序都是通过 Web 访问的,因此该名称似乎是最合适的。

Many of the performance improvements made to Kestrel came not from the ASP.NET team members themselves, but from contributors to the open-source project on GitHub (https://github.com/dotnet/aspnetcore). Developing in the open means that you typically see fixes and features make their way to production faster than you would for the previous version of ASP.NET, which was dependent on .NET Framework and Windows and, as such, had long release cycles.

对 Kestrel 所做的许多性能改进并非来自 ASP.NET 团队成员本身,而是来自 GitHub (https://github.com/dotnet/aspnetcore) 上开源项目的贡献者。以开放方式进行开发意味着您通常会看到修复程序和功能比以前版本的 ASP.NET 更快地进入生产环境,该版本依赖于 .NET Framework 和 Windows,因此具有较长的发布周期。

By contrast, .NET 5+ and hence ASP.NET Core are designed to be released in small increments. Major versions will be released on a predictable cadence, with a new version every year and a new LTS version released every two years (http://mng.bz/1qrg). In addition, bug fixes and minor updates can be released as and when they’re needed.Additional functionality is provided in NuGet packages independent of the underlying .NET 5+ platform.
相比之下,.NET 5+ 和 ASP.NET Core 旨在以小增量发布。主要版本将以可预测的节奏发布,每年发布一个新版本,每两年 (http://mng.bz/1qrg) 发布一个新的 LTS 版本。此外,可以在需要时发布错误修复和次要更新。NuGet 包中提供了独立于基础 .NET 5+ 平台的其他功能。

NOTE NuGet is a package manager for .NET that enables you to import libraries into your projects. It’s equivalent to Ruby Gems, npm for JavaScript, or Maven for Java.

注意: NuGet 是 .NET 的包管理器,可用于将库导入到项目中。它等效于 Ruby Gems、用于 JavaScript 的 npm 或用于 Java 的 Maven。

To enable this approach to releases, ASP.NET Core is highly modular, with as little coupling to other features as possible. This modularity lends itself to a pay-for-play approach to dependencies, where you start with a bare-bones application and add only the libraries you require, as opposed to the kitchen-sink approach of previous ASP.NET applications. Even MVC is an optional package! But don’t worry—this approach doesn’t mean that ASP.NET Core is lacking in features, only that you need to opt into them. Some of the key infrastructure improvements include

为了实现这种发布方法,ASP.NET Core 是高度模块化的,尽可能少地与其他功能耦合。这种模块化性适用于依赖项的付费方法,在这种方法中,您从一个基本的应用程序开始,只添加您需要的库,而不是以前的 ASP.NET 应用程序的厨房接收器方法。甚至 MVC 也是一个可选包!但别担心,这种方法并不意味着 ASP.NET Core 缺少功能,只是您需要选择使用这些功能。一些关键的基础设施改进包括

  • Middleware pipeline for defining your application’s behavior
    用于定义应用程序行为的中间件管道

  • Built-in support for dependency injection
    对依赖项注入的内置支持

  • Combined UI (MVC) and API (web API) infrastructure
    组合的 UI (MVC) 和 API (Web API) 基础设施

  • Highly extensible configuration system Standardized, extensible logging system
    高度可扩展的配置系统 标准化、可扩展的日志记录系统

  • Uses asynchronous programming by default for
    默认情况下使用异步编程

  • built-in scalability on cloud platforms
    云平台上的内置可扩展性

Each of these features was possible in the previous version of ASP.NET but required a fair amount of additional work to set up. With ASP.NET Core, they’re all there, ready and waiting to be connected.
这些功能在以前的 ASP.NET 版本中都是可能的,但需要相当多的额外工作才能建立。有了 ASP.NET Core,它们都已准备就绪,等待连接。

Microsoft fully supports ASP.NET Core, so if you want to build a new system, there’s no significant reason not to use it. The largest obstacle you’re likely to come across is wanting to use programming models that are no longer supported in ASP.NET Core, such as Web Forms or WCF Server, as I’ll discuss in the next section.

Microsoft 完全支持 ASP.NET Core,因此如果您想构建一个新系统,没有明显的理由不使用它。您可能遇到的最大障碍是希望使用 ASP.NET Core 中不再支持的编程模型,例如 Web 窗体或 WCF Server,我将在下一节中讨论。

I hope that this section whetted your appetite to use ASP.NET Core for building new applications. But if you’re an existing ASP.NET developer considering whether to convert an existing ASP.NET application to ASP.NET Core, that’s another question entirely.

我希望本节能激发您使用 ASP.NET Core 构建新应用程序的兴趣。但是,如果你是现有的 ASP.NET 开发人员,正在考虑是否将现有的 ASP.NET 应用程序转换为 ASP.NET Core,那完全是另一个问题。

2.4.3 Converting an existing ASP.NET application to ASP.NET Core‌

2.4.3 将现有 ASP.NET 应用程序转换为 ASP.NET Core

By contrast with new applications, an existing application presumably already provides value, so there should always be a tangible benefit to performing what may amount to a significant rewrite in converting from ASP.NET to ASP.NET Core. The advantages of adopting ASP.NET Core are much the same as those for new applications: cross-platform deployment, modular features, and a focus on performance. Whether the benefits are sufficient will depend largely on the particulars of your application, but some characteristics make conversion more difficult:

与新应用程序相比,现有应用程序可能已经提供了价值,因此在从 ASP.NET 转换为 ASP.NET Core 的过程中执行可能相当于重大重写的作应该始终会带来切实的好处。采用 ASP.NET Core 的优势与新应用程序的优势大致相同:跨平台部署、模块化功能和对性能的关注。好处是否足够在很大程度上取决于您的应用程序的具体情况,但有些特征使转换更加困难:

  • Your application uses ASP.NET Web Forms.
    您的应用程序使用 ASP.NET Web Forms。

  • Your application is built with WCF.
    您的应用程序是使用 WCF 构建的。

  • Your application is large, with many advanced MVC features.
    您的应用程序很大,具有许多高级 MVC 功能。

If you have an ASP.NET Web Forms application, attempting to convert it directly to ASP.NET Core isn’t advisable. Web Forms is inextricably tied to System.Web.dll and IIS, so it will likely never be available in ASP.NET Core. Converting an application to ASP.NET Core effectively involves rewriting the application from scratch, not only shifting frameworks, but also potentially shifting design paradigms.

如果您有 ASP.NET Web Forms 应用程序,则不建议尝试将其直接转换为 ASP.NET Core。Web 表单与 System.Web.dll 和 IIS 有着千丝万缕的联系,因此它可能永远不会在 ASP.NET Core 中提供。将应用程序有效地转换为 ASP.NET Core 涉及从头开始重写应用程序,不仅要改变框架,还可能改变设计范式。

All is not lost, however. Blazor server provides a stateful, component-based application that’s similar to the Web Forms application model. You may be able to gradually migrate your Web Forms application page by page to an ASP.NET Core Blazor server application.4 Alternatively, you could slowly introduce web API concepts into your Web Forms application, reducing the reliance on legacy Web Forms constructs such as ViewState, with the goal of ultimately moving to an ASP.NET Core web API application.

然而,一切都没有失去。Blazor 服务器提供基于组件的有状态应用程序,它类似于 Web Forms 应用程序模型。你可以逐步逐页将 Web 窗体应用程序迁移到 ASP.NET Core Blazor 服务器应用程序。4 或者,您可以慢慢地将 Web API 概念引入 Web 窗体应用程序,从而减少对旧版 Web 窗体构造(如 ViewState)的依赖,最终迁移到 ASP.NET Core Web API 应用程序。

Windows Communication Foundation (WCF) is only partially supported in ASP.NET Core. It’s possible to build client-side WCF services using the libraries provided by ASP.NET Core (https://github.com/dotnet/wcf) and to build server-side WCF services by using the Microsoft-supported community-driven project CoreWCF.5 These libraries don’t support all the APIs available in .NET Framework WCF (distributed transactions and some message security formats, for example), so if you absolutely need those APIs, it may be best to avoid ASP.NET Core for now.

服务,也可以使用 Microsoft 支持的社区驱动项目 CoreWCF 构建服务器端 WCF 服务。5 这些库不支持 .NET Framework WCF 中提供的所有 API(例如,分布式事务和某些消息安全格式),因此,如果您绝对需要这些 API,最好暂时避免使用 ASP.NET Core。

TIP If you like WCF’s contract-based RPC-style of programming but don’t have a hard requirement for WCF itself, consider using gRPC instead. gRPC is a modern RPC framework with many concepts that are similar to WCF, and it’s supported by ASP.NET Core out of the box (http://mng.bz/wv9Q).

提示 如果您喜欢 WCF 基于协定的 RPC 样式编程,但对 WCF 本身没有硬性要求,请考虑改用 gRPC。gRPC 是一个现代 RPC 框架,具有许多与 WCF 类似的概念,并且它由开箱即用的 ASP.NET Core (http://mng.bz/wv9Q) 提供支持。

If your existing application is complex and makes extensive use of the previous MVC or web API extensibility points or message handlers, porting your application to ASP.NET Core may be more difficult. ASP.NET Core is built with many features similar to the previous version of ASP.NET MVC, but the underlying architecture is different. Several of the previous features don’t have direct replacements, so they’ll require rethinking.

如果现有应用程序很复杂,并且广泛使用以前的 MVC 或 Web API 扩展点或消息处理程序,则将应用程序移植到 ASP.NET Core 可能会更加困难。ASP.NET Core 具有许多与以前版本的 ASP.NET MVC 类似的功能,但底层架构不同。前面的几个功能没有直接替换,因此需要重新考虑。

The larger the application is, the greater the difficulty you’re likely to have converting your application to ASP.NET Core.Microsoft itself suggests that porting an application from ASP.NET MVC to ASP.NET Core is at least as big a rewrite as porting from ASP.NET Web Forms to ASP.NET MVC. If that suggestion doesn’t scare you, nothing will!

应用程序越大,将应用程序转换为 ASP.NET Core 的难度就越大。
Microsoft本身表明,将应用程序从 ASP.NET MVC 移植到 ASP.NET Core 至少与从 ASP.NET Web Forms 移植到 ASP.NET MVC 一样大。如果这个建议没有吓到你,那就什么都不会了!

If an application is rarely used, isn’t part of your core business, or won’t need significant development in the near term, I suggest that you don’t try to convert it to ASP.NET Core. Microsoft will support .NET Framework for the foreseeable future (Windows itself depends on it!), and the
payoff in converting these fringe applications is unlikely to be worth the effort.

如果某个应用程序很少使用,不是您的核心业务的一部分,或者在短期内不需要重大开发,我建议您不要尝试将其转换为 ASP.NET Core。Microsoft 将在可预见的将来支持 .NET Framework(Windows 本身依赖于它!),并且

转换这些边缘应用程序的回报不太可能值得付出努力。

So when should you port an application to ASP.NET Core? As I’ve already mentioned, the best opportunity to get started is on small new greenfield projects instead of existing applications. That said, if the existing application in question is small or will need significant future development, porting may be a good option.

那么,何时应将应用程序移植到 ASP.NET Core?正如我已经提到的,最好的开始机会是小型的新绿地项目,而不是现有的应用程序。也就是说,如果现有应用程序很小或未来需要大量开发,则移植可能是一个不错的选择。

It’s always best to work in small iterations if possible when porting an application, rather than attempt to convert the entire application at the same time. Luckily, Microsoft provides tools for that purpose. A set of System.Web adapters, a .NET-based reverse proxy called YARP (Yet Another Reverse Proxy; http://mng.bz/qr92), and tooling built into Visual Studio can help you implement the strangler fig pattern (http://mng.bz/rW6J). This tooling allows you to migrate your application one page/API at a time, reducing the risk associated with porting an ASP.NET application to ASP.NET Core.

在移植应用程序时,如果可能的话,最好在小迭代中工作,而不是尝试同时转换整个应用程序。幸运的是,Microsoft 提供了用于此目的的工具。一组 System.Web 适配器、一个 .基于 NET 的反向代理称为 YARP(Yet Another Reverse Proxy; http://mng.bz/qr92) 和 Visual Studio 中内置的工具可以帮助您实现 strangler fig 模式 (http://mng.bz/rW6J)。借助此工具,您可以一次迁移一个页面/API 的应用程序,从而降低将 ASP.NET 应用程序移植到 ASP.NET Core 的相关风险。

In this chapter, we walked through some of the historical context of ASP.NET Core, as well as some of the advantages of adopting it. In chapter 3, you’ll create your first application from a template and run it. We’ll walk through each of the main components that make up your application and see how they work together to render a web page.‌

在本章中,我们介绍了 ASP.NET Core 的一些历史背景,以及采用它的一些优势。在第 3 章中,您将从模板创建第一个应用程序并运行它。我们将介绍构成应用程序的每个主要组件,并了解它们如何协同工作以呈现网页。

Summary

总结

  • Web frameworks provide a way to build dynamic web applications easily.
    Web 框架提供了一种轻松构建动态 Web 应用程序的方法。

  • ASP.NET Core is a web framework built with modern software architecture practices and modularization as its focus.
    ASP.NET Core 是一个以现代软件架构实践和模块化为重点构建的 Web 框架。

  • ASP.NET Core runs on the cross-platform .NET 7 platform. You can access Windows-specific features such as the Windows Registry by using the Windows Compatibility Pack.
    ASP.NET Core 在跨平台的 .NET 7 平台上运行。您可以使用 Windows 兼容包访问特定于 Windows 的功能,例如 Windows 注册表。

  • .NET 5, .NET 6, and .NET 7 are the next versions of .NET Core after .NET Core 3.1.
    .NET 5、.NET 6 和 .NET 7 是.NET Core 3.1 之后的 .NET Core的下一个版本。

  • ASP.NET Core is best used for new greenfield projects.
    ASP.NET Core 最适合用于新的绿地项目。

  • Legacy technologies such as WCF Server and Web Forms can’t be used directly with ASP.NET Core, but they have analogues and supporting libraries that can help with porting ASP.NET applications to ASP.NET Core.
    WCF Server 和 Web Forms 等旧技术不能直接与 ASP.NET Core 一起使用,但它们具有类似物和支持库,可帮助将 ASP.NET 应用程序移植到 ASP.NET Core。

  • You can convert an existing ASP.NET application to ASP.NET Core gradually by using the strangler fig pattern, using tooling and libraries provided by Microsoft.
    通过使用 strangler fig 模式,您可以使用 Microsoft 提供的工具和库,逐步将现有的 ASP.NET 应用程序转换为 ASP.NET Core。

  • ASP.NET Core apps are often protected from the internet by a reverse-proxy server, which forwards requests to the application.
    ASP.NET Core 应用程序通常由反向代理服务器保护,不受 Internet 的影响,该服务器将请求转发到应用程序。


1.Orchard Core (https://orchardcore.net). Source code at https://github.com/OrchardCMS/OrchardCore.

2.The cloudscribe project (https://www.cloudscribe.com). Source code at https://github.com/cloudscribe.

3.As always in web development, technology is in a constant state of flux, so these benchmarks will evolve over time. Although ASP.NET Core may not maintain its top-10 slot, you can be sure that performance is one of the key focal points of the ASP.NET Core team.

4.There is a community-driven effort to create Blazor versions of common WebForms components (http://mng.bz/PzPP). Also see an e-book for Blazor for Web Forms developers at http://mng.bz/JgDv.

5.You can find the CoreWCF libraries at https://github.com/corewcf/corewcf and details on upgrading a WCF service to .NET 5+ at http://mng.bz/mVg2.

Leave a Reply

Your email address will not be published. Required fields are marked *