理解ASP.NET核心请求和反应管道----第一部分:概述和基础 (中文 (Chinese Simplified))

理解ASP.NET核心请求和反应管道----第一部分:概述和基础

Sunday, 09 November 2025

//

5 minute read

一. 导言 导言 导言 导言 导言 导言 一,导言 导言 导言 导言 导言 导言

ASP.NET核心请求和响应管道是基于这一框架的每一个网络应用程序的支柱。

了解请求如何通过您的应用程序流动,如何产生回应,对于建立高效、可维持和安全的网络应用程序至关重要。

从HTTP请求到达您的服务器到回复被发回客户端, 这个系列将指导您通过管道的每一个层次。

无论是建立API,网络应用程序,还是微服务, 管道总是在那里, 在幕后工作。

通过深入理解它,你将能够优化业绩, 以优雅的方式实施交叉关注, 更有效地解决问题。

备注:这是我在AI/一种花费1000美元Clude Code Web信用的实验的一部分。**我为这篇论文、我的理解、我不得不提出来的问题 提供了大量的资料。**这很有趣,填补了一个空白 我还没有看到填补 其他地方。

  1. **什么是请求管道?**核心是ASP.NET核心请求编审程序,这是处理HTTP请求和生成HTTP答复的一系列组成部分。
  2. **将它视为工厂中的传送带:请求一端进入,通过检查、修改或采取行动的不同站点(部件),最终在另一端作出反应。**此架构基于
  3. 中中器体图案,其中每个组成部分(中器)都负有具体责任,并能够:

处理收到的请求

在转交给下一部分之前

flowchart TB
    OS[Operating System and Network TCP IP Socket Layer]
    Kestrel[Kestrel Web Server HTTP11 HTTP2 HTTP3 QUIC TLS SSL Termination Connection Management]
    Host[Host Layer Application Lifetime Dependency Injection Configuration Logging]

    subgraph Middleware_Pipeline [Middleware Pipeline]
        EH[Exception Handler Middleware catches exceptions]
        HTTPS[HTTPS Redirection Middleware redirects HTTP to HTTPS]
        Static[Static Files Middleware serves static content]
        Routing[Routing Middleware matches request to endpoint]
        AuthN[Authentication Middleware validates identity]
        AuthZ[Authorization Middleware validates permissions]
        Custom[Custom Middleware app specific logic]
        EndpointMW[Endpoint Middleware executes matched endpoint]
    end

    EndpointExec[Endpoint Execution MVC Controllers and Actions Razor Pages Minimal APIs gRPC SignalR]
    Response[Response Generation flows back through middleware]
    BackKestrel[Back to Kestrel]
    Client[Back to Client]

    OS --> Kestrel --> Host --> EH --> HTTPS --> Static --> Routing --> AuthN --> AuthZ --> Custom --> EndpointMW --> EndpointExec --> Response --> BackKestrel --> Client

短路输油管

立即作出反应

处理即将发送的响应

在下一个部件执行后

高级别架构

让我们想象一下ASP.NET核心8:

  • 请求流程:穿越管道的旅程
  • 让我们遵循一个典型的HTTP请求,
    1. 目标 1. 目标HttpContext网络图层
  • 当客户向您的应用程序提出请求时, 它会以原始 TCP/IP 包形式到达您的服务器 。

操作系统的网络堆叠将这些包组装成完整的HTTP要求。

  1. 目标
  • Kestrel Web 服务器
  • Kestrel, ASP.NET Core的跨平台网络服务器收到请求。
  • 凯斯特尔:
  • 分析 HTTP 协议( HTTP/1.1、 HTTP/2 或 HTTP/3)

如果使用 HTTPPS, 处理 TLS/ SSL 解密

创建

  • 对象既代表请求,又代表响应HttpContext
  • 控制应用程序中器件管道的出入控制
  • 3 个
  • 主机图层
  • 东道主提供执行环境。

它:

管理应用程序使用寿命

  • 提供依赖性注射容器
  • 用品配置和伐木基础设施
  • 启动中器输油管
    1. 4个。
  • 中器元管道

这就是你应用逻辑的起点

每个中器组件 :

接收

  • 履行具体职能
  • 决定是调用下一个中继器还是短路
  • 在将请求转交之前可以修改请求
  • 可在答复回来后修改答复

5 个

sequenceDiagram
    autonumber
    participant Client
    participant OS as OS/Network
    participant Kestrel
    participant Host
    participant MW as Middleware Pipeline
    participant Endpoint as Endpoint Execution

    Client->>OS: HTTP request
    OS->>Kestrel: Forward request
    Kestrel->>Host: Create HttpContext
    Host->>MW: Invoke pipeline
    MW->>Endpoint: Route matched, execute
    Endpoint-->>MW: Response
    MW-->>Kestrel: Response after post-processing
    Kestrel-->>OS: Send HTTP response
    OS-->>Client: Response delivered

结束点执行

如果请求通过所有中继器件,它达到终点:

MVC的控制器动作HttpContextRazor Pages 中的页面处理器

public abstract class HttpContext
{
    // The incoming request
    public abstract HttpRequest Request { get; }

    // The outgoing response
    public abstract HttpResponse Response { get; }

    // User identity and authentication
    public abstract ClaimsPrincipal User { get; set; }

    // Request-scoped services
    public abstract IServiceProvider RequestServices { get; set; }

    // Connection information
    public abstract ConnectionInfo Connection { get; }

    // WebSocket support
    public abstract WebSocketManager WebSockets { get; }

    // Request cancellation
    public abstract CancellationToken RequestAborted { get; set; }

    // Session state
    public abstract ISession Session { get; }

    // Generic feature collection
    public abstract IFeatureCollection Features { get; }

    // And more...
}

Minimal APIs 中的路由处理器HttpContext.

GRPC服务方法

信号路枢纽法

// Basic middleware signature
public delegate Task RequestDelegate(HttpContext context);

// Middleware can be implemented as a method
app.Use(async (context, next) =>
{
    // Do something before the next middleware
    Console.WriteLine($"Request: {context.Request.Path}");

    // Call the next middleware
    await next(context);

    // Do something after the next middleware
    Console.WriteLine($"Response: {context.Response.StatusCode}");
});

终点执行您的商业逻辑, 并产生响应 。

6 . 6 . 6 .

public delegate Task RequestDelegate(HttpContext context);

回应流动

反应回流到中件管道:

每个中继器能检查或修改反应

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

// Middleware 1: Logging
app.Use(async (context, next) =>
{
    Console.WriteLine($"[{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] Request started: {context.Request.Method} {context.Request.Path}");

    await next(context);

    Console.WriteLine($"[{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] Request finished: {context.Response.StatusCode}");
});

// Middleware 2: Custom header
app.Use(async (context, next) =>
{
    context.Response.Headers["X-Custom-Header"] = "Hello from middleware!";

    await next(context);
});

// Middleware 3: Short-circuit for specific path
app.Use(async (context, next) =>
{
    if (context.Request.Path == "/health")
    {
        context.Response.StatusCode = 200;
        await context.Response.WriteAsync("Healthy");
        return; // Short-circuit - don't call next()
    }

    await next(context);
});

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

app.Run();

标头最终定稿http://localhost:5000/答复机构是书面的

Console output:
[2024-01-15 10:30:45] Request started: GET /
[2024-01-15 10:30:45] Request finished: 200

Browser output:
Hello World!

Response headers:
X-Custom-Header: Hello from middleware!

Kestreel 将 HTTP 回复发送到客户端http://localhost:5000/health:

Console output:
[2024-01-15 10:30:50] Request started: GET /health
[2024-01-15 10:30:50] Request finished: 200

Browser output:
Healthy

Response headers:
X-Custom-Header: Hello from middleware!

请求/响应序列图/health关键概念

HttpConttext 文本

缩略

  1. **是管道中的核心物体。**它概括如下:

  2. 您需要知道的关于当前请求的一切信息 以及您需要建立响应的所有信息 通过中中器

  3. Midleware是管道的构件最简单的中件是处理请求的函数 :

  4. 请求代表请求授权是一种能够处理 HTTP 请求的职能。

  5. **整个中件输油管都是由一系列请求代表建造的:**每个中间软件包住下一个代表, 创建一个嵌套的电话链。

简单示例

让我们看看一个最小的 ASP. NET核心8 应用 演示输油管:

当你访问时

  • **,你会看到:**当你访问时

  • 注意第三个中中器短路 如何将输油管连接到路径,但是在它被执行之前,所有中间软件都还在执行中。

  • 为何要了解管道问题了解管道至关重要,因为:

  • 业绩优化了解执行顺序有助于适当安排昂贵的操作,避免不必要的工作。

  • 交叉关注问题: Midleward 是执行记录、认证、错误处理和其他影响所有请求的关切的完美工具。IStartupFilter, IHostedService除调调

:当事情出错时,了解管道有助于你确定问题发生地点。

  • 自定义扩展名
  • :您可以创建强大的自定义中继器,以扩展框架的能力。
  • HttpContext安全安全安全安全安全安全安全安全
  • :了解如何将认证和授权纳入管道对于确保申请安全至关重要。
  • 下一个是什么?

在第一部分,我们已经建立了基础 通过理解管道是什么, 其结构如何, 以及请求是如何通过它流动的。

Finding related posts...
logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.