ASP.NET Core Features 详解:基于 practical-aspnetcore 仓库的 11 个运行时特性(Feature)实战样例

原创2026-10-14 11:49:051,744 阅读
文章标签:示例工程

ASP.NET Core Features 详解:基于 practical-aspnetcore 仓库的 11 个运行时特性(Feature)实战样例

Features 是 ASP.NET Core 框架在请求管道中暴露的一组"运行时可获取对象"的统称:每个 Feature 接口封装一类特定的服务器或请求信息(监听地址、连接端点、会话、请求体大小上限、响应写出通道等),开发者可以在任意中间件或端点里通过 context.Features.Get<T>() 或 IServer.Features.Get<T>() 取到并操作它们。本文以 practical-aspnetcore 仓库 projects/features 目录下的 11 个可运行样例为主体,逐一讲解每个 Feature 的接口、典型用法与源码细节,读完后你将掌握如何在中间件管道中读取、设置乃至替换各种内置与自定义 Feature。

什么是 Feature

README 对这一主题的定义非常简洁:"Features are collection of objects you can obtain from the framework at runtime that serve different purposes"(Features 是一组在运行时从框架获取、用途各异的对象)。

从源码结构看,Feature 机制由两层支撑:

  • 请求级:每个 HttpContext 都带有一个 IFeatureCollection(即 context.Features),框架在请求到达时把与本次请求相关的对象(请求、响应、连接、会话等)注册进去,管道中的任何组件都可以 Get<T>() 读取、Set<T>() 写入。
  • 服务器级:IServer.Features(Microsoft.AspNetCore.Hosting.Server.Features)存放的是整个服务器实例的属性,例如监听地址集合。

仓库中这 11 个样例都是独立的最小化 Web 项目,每个项目目录下只有一个 Program.cs 和一个 csproj(部分项目另附 json 配置),从各 csproj 文件看,当前统一目标框架为 net10.0、启用隐式 using 与 preview 语言版本,例如 features-server-addresses.csproj。任意一个都可以用 dotnet run 直接运行验证。

下面按 README 的目录顺序逐一展开。

1. Server Addresses Feature:获取应用监听的 URL 列表

样例:features-server-addresses

IServerAddressesFeature 暴露 Addresses 集合,即应用当前正在响应(监听)的全部 URL。README 的描述是:"Use this Feature to obtain a list of urls that your app is responding to."

using Microsoft.AspNetCore.Hosting.Server.Features;

var app = WebApplication.Create();
var serverAddress = (app as IApplicationBuilder).ServerFeatures.Get<IServerAddressesFeature>();
app.Run(context =>
{
    var str = string.Empty;
    foreach(var a in serverAddress.Addresses)
    {
        str += $"{a}\n";
    }
    return context.Response.WriteAsync(str);
});

app.Run();

注意取法:这里在 app.Run() 启动之前,先把 WebApplication 实例显式转换为 IApplicationBuilder,再从 ServerFeatures 中取出 IServerAddressesFeature,然后把地址列表在每次响应中写出。这体现了服务器级 Feature 与请求级 Feature 的区别——它挂在 IServer 上而不是 HttpContext 上,整个应用生命周期内只有一份。

2. Server Addresses Feature - 2:通过 IServer 在中间件中获取地址

样例:features-server-addresses-2

README 说明此场景:"Use IServer interface to access server addresses when you don't have access to IApplicationBuilder." 即当你身处中间件内部、拿不到 IApplicationBuilder 时,可以注入 IServer(Microsoft.AspNetCore.Hosting.Server)间接拿到 IServer.Features:

using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Hosting.Server;

var app = WebApplication.Create();
app.UseMiddleware<AddressesMiddleware>();
app.Run();

public class AddressesMiddleware
{
    IServer _server;

    IReadOnlyCollection<string> _addresses;

    public AddressesMiddleware(RequestDelegate next, IServer server)
    {
        _server = server;
    }

    public async Task Invoke(HttpContext context)
    {
        var str = string.Empty;

        // We cache the result because the addresses are not going to change.
        // Remember middlewares are singletons, so we can just do this simple check.
        if (_addresses == null)
        {
            var address = _server.Features.Get<IServerAddressesFeature>();
            _addresses = address.Addresses.ToList();
        }

        foreach (var a in _addresses)
        {
            str += $"{a}\n";
        }

        await context.Response.WriteAsync(str);
    }
}

这段代码有两个值得注意的实现细节:

  1. 构造函数注入 IServer:中间件由 DI 容器创建,IServer 是容器中的单例,通过构造函数注入即可在管道内部访问服务器级 Feature。
  2. 惰性缓存结果:源码注释解释了原因——监听地址在运行期间不会变化,而中间件是单例,因此用一次 null 检查把 Addresses 缓存到 _addresses 字段,避免每个请求都重复读取。这个"单例 + 简单 null 检查"的写法是仓库中演示的性能习惯(当然在并发首次请求下并非严格线程安全,样例取其简洁)。

3. Request Feature:直接操作请求对象

样例:features-server-request

IHttpRequestFeature 暴露原始请求对象。README 提醒:它与 HttpContext.Request 有相似之处,但"两者不相等,HttpContext.Request 拥有更多属性"(即 HttpRequest 是更高层的封装,Feature 更接近底层数据)。

using Microsoft.AspNetCore.Http.Features;

var app = WebApplication.Create();

app.Use(async (context, next) =>
{
    var request = context.Features.Get<IHttpRequestFeature>();
    request.Headers.Append("greetings", "hello world");
    await next.Invoke();
});

app.Run(context =>
{
    return context.Response.WriteAsync($"hello {context.Request.Headers["greetings"]}");
});

app.Run();

该样例演示了 Feature 机制的一个实用能力:前一个中间件通过 Feature 拿到请求的 Headers 并追加 greetings: hello world,下游端点随即能通过 context.Request.Headers["greetings"] 读到,响应输出 hello hello world。由于 Feature 与 HttpRequest 共享同一底层数据,跨组件修改头信息是可见的。

4. Connection Feature:本地/远程 IP、端口与连接 ID

样例:features-connection

README 描述:"Use IHttpConnectionFeature interface to obtain local ip/port and remote ip/port."

using Microsoft.AspNetCore.Http.Features;

var app = WebApplication.Create();
app.Run(context =>
{
    var connection = context.Features.Get<IHttpConnectionFeature>();
    var str = string.Empty;
    str += $"Local IP:Port: {connection?.LocalIpAddress}:{connection?.LocalPort}\n";
    str += $"Remote IP:Port: {connection?.RemoteIpAddress}:{connection?.RemotePort}\n";
    str += $"Connection Id: {connection?.ConnectionId}\n";

    return context.Response.WriteAsync($"{str}");
});

app.Run();

响应输出类似:

Local IP:Port: 127.0.0.1:5000
Remote IP:Port: 127.0.0.1:54321
Connection Id: 0H...

IHttpConnectionFeature 还提供 ConnectionId(Kestrel 生成的唯一连接标识),常用于日志追踪与调试连接级问题。样例中全程使用 ?. 空值访问,说明在极端托管环境下 Feature 理论上可能为 null,这是值得保留的防御写法。

5. Custom Feature:自定义并在中间件中传递 Feature

样例:features-server-custom

README 描述:"Create your own custom Feature and pass it along from a middleware."

var app = WebApplication.Create();

app.Use(async (context, next ) =>{
    context.Features.Set<ICustomFeature>(new CustomFeature());
    await next.Invoke();
});

app.Run(context =>
{
    var custom = context.Features.Get<ICustomFeature>();
    if (custom == null)
        return context.Response.WriteAsync($"Custom is null");
    else
        return context.Response.WriteAsync($"{custom.Greetings}");
});

app.Run();

interface ICustomFeature
{
    string Greetings {get;}
}

public class CustomFeature : ICustomFeature
{
    public string  Greetings => "This is my custom feature set from previous middleware";
}

这里展示了 Feature 机制的完整自定义闭环:

  1. 定义接口 ICustomFeature(放在 Microsoft.AspNetCore.Http.Features 命名空间下即可被 IFeatureCollection 泛型方法识别,当然自定义接口用任何命名空间均可);
  2. 前一个中间件 context.Features.Set<ICustomFeature>(...) 写入;
  3. 下游端点 context.Features.Get<ICustomFeature>() 读取,并做了 null 判空分支。

响应输出为 This is my custom feature set from previous middleware。

6. Custom Feature - Override:在管道中替换 Feature 实现

样例:features-server-custom-override

README 描述:"Shows how you can replace an implementation of a Feature with another within the request pipeline." Set<T>() 对同一接口重复调用会覆盖旧实例,这一特性可用于"中途换装":

var app = WebApplication.Create();

app.Use(async (context, next) =>
   {
       context.Features.Set<ICustomFeature>(new CustomFeature("First greeting"));
       await next.Invoke();
   });

app.Use(async (context, next) =>
{
    var custom = context.Features.Get<ICustomFeature>();
    await context.Response.WriteAsync($"{custom?.Greetings}\n");
    context.Features.Set<ICustomFeature>(new CustomFeature("Second greeting"));
    await next.Invoke();
});

app.Run(context =>
{
    var custom = context.Features.Get<ICustomFeature>();
    return context.Response.WriteAsync($"{custom?.Greetings}");
});

app.Run();

interface ICustomFeature
{
    string Greetings { get; }
}

public class CustomFeature : ICustomFeature
{
    string _greetings;

    public CustomFeature(string greetings)
    {
        _greetings = greetings;
    }

    public string Greetings => _greetings;
}

执行顺序清晰地展示了覆盖语义:中间件 1 设置 "First greeting";中间件 2 先读出旧值(输出 First greeting),再 Set 为 "Second greeting";最终端点读到的就是新实例,输出 Second greeting。同一请求内,后 Set 者生效。

7. Request Culture Feature:检测请求文化

样例:features-request-culture

README 描述:"Use this feature to detect the culture of a web request through IRequestCultureFeature."

using Microsoft.AspNetCore.Localization;

var app = WebApplication.Create();
app.UseRequestLocalization();

app.Run(async context =>
{
    var cultureFeature = context.Features.Get<IRequestCultureFeature>();
    await context.Response.WriteAsync($"Request culture: {cultureFeature?.RequestCulture.Culture.EnglishName}");
});

app.Run();

关键点:IRequestCultureFeature 由 UseRequestLocalization() 中间件注册。该中间件会依据 RequestLocalizationOptions(支持 query 参数、Accept-Language 头等多种 IRequestCultureProvider)解析出请求文化,并写入 context.Features。端点随后取 cultureFeature.RequestCulture.Culture.EnglishName 输出文化的英文名称,例如 English (United States)。没有先执行 UseRequestLocalization() 时,Get<IRequestCultureFeature>() 会返回 null。

8. Session Feature:在中间件中使用内存 Session

样例:features-session

README 描述:"Use session within your middlewares. This sample shows a basic usage of in memory session."

using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

var app = builder.Build();
app.UseSession();

app.Use(async (context, next) =>
{
    var session = context.Features.Get<ISessionFeature>();
    try
    {
        session.Session.SetString("Message", "Hello world");
        session.Session.SetInt32("Year", DateTime.Now.Year);
    }
    catch (Exception ex)
    {
        await context.Response.WriteAsync($"{ex.Message}");
    }
    await next.Invoke();
});

app.Run(async context =>
{
    var session = context.Features.Get<ISessionFeature>();

    try
    {
        string msg = session.Session.GetString("Message");
        int? year = session.Session.GetInt32("Year");
        await context.Response.WriteAsync($"{msg} {year}");
    }
    catch (Exception ex)
    {
        await context.Response.WriteAsync($"{ex.Message}");
    }
});

app.Run();

从源码结构看,这里体现的是"用 Feature 而不是扩展方法访问 Session"的路径:

  • 注册链路:AddDistributedMemoryCache()(内存版 IDistributedCache)+ AddSession(),管道中必须 app.UseSession(),之后 ISessionFeature 才会在 context.Features 中可用;
  • ISessionFeature.Session 暴露 ISession 对象,支持 SetString / GetInt32 / GetString / GetInt32 等强类型快捷方法;
  • 样例选择在前置中间件写、末端端点读,正是 README 强调的"在中间件中使用 session"的典型场景;两处都包了 try/catch,因为 Session 在响应已开始写入后再读会抛 InvalidOperationException,这是 Session 使用的常见坑点。

9. Session Feature with Redis:用 Redis 存储 Session

样例:features-session-redis-2

README 描述:"Use session within your middlewares. This sample uses Redis to store session data."

using System.Text.Json;
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["redisConnectionString"];
});

builder.Services.AddSession();

var app = builder.Build();

app.UseSession();

app.Use(async (context, next) =>
{
    var person = new Person
    {
        FirstName = "Anne",
        LastName = "M"
    };

    var session = context.Features.Get<ISessionFeature>();
    try
    {
        session.Session.SetString("Message", "Buon giorno cuore");
        session.Session.SetInt32("Year", DateTime.Now.Year);
        session.Session.SetString("Amore", JsonSerializer.Serialize(person));
    }
    catch (Exception ex)
    {
        await context.Response.WriteAsync($"{ex.Message}");
    }
    await next.Invoke();
});

app.Run(async context =>
{
    var session = context.Features.Get<ISessionFeature>();

    try
    {
        string msg = session.Session.GetString("Message");
        int? year = session.Session.GetInt32("Year");
        var amore = JsonSerializer.Deserialize<Person>(session.Session.GetString("Amore"));

        await context.Response.WriteAsync($"{amore.FirstName}, {msg} {year}");
    }
    catch (Exception ex)
    {
        await context.Response.WriteAsync($"{ex.Message}");
    }
});

app.Run();

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

与内存版相比,此样例只改动了一处依赖注册:AddDistributedMemoryCache() 换成 AddStackExchangeRedisCache(),连接串取自配置项 redisConnectionString。项目通过 features-session-redis-2.csproj 引用了 Microsoft.Extensions.Caching.StackExchangeRedis 包(版本 10.0.11),配置位于 appSettings.json:

{
    "redisConnectionString": "localhost:6379"
}

因此适用前提是本机 6379 端口有一个可用的 Redis 实例。此外样例还演示了 Session 存复杂对象的方式:ISession 本身只能存字符串等原始类型,所以用 System.Text.Json 把 Person 序列化后存入 SetString("Amore", ...),读取时再 Deserialize<Person> 还原,最终响应类似 Anne, Buon giorno cuore 2026。

10. Maximum Request Body Size Feature:读取与设置请求体大小上限

样例:features-max-request-body-size

README 描述:"Use this feature to read and set maximum HTTP Request body size."

using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder();
builder.WebHost.ConfigureKestrel(k =>
{
    k.Limits.MaxRequestBodySize = 5000;
});

var app = builder.Build();

app.Run(context =>
{
    var bodySize = context.Features.Get<IHttpMaxRequestBodySizeFeature>();
    bodySize.MaxRequestBodySize = 555;
    var str = "<html><body>";
    str += $"Max Request Body Size {bodySize.MaxRequestBodySize}(Is Read Only: {bodySize.IsReadOnly}) You can <strong>also</strong> set this value at KestrelServerOptions.Limits.MaxRequestBodySize";
    str += "</body></html>";
    context.Response.Headers.Append("Content-Type", "text/html");
    return context.Response.WriteAsync($"{str}");
});

app.Run();

该样例把两个层面的配置串起来:

  • 服务器层(默认上限):ConfigureKestrel 中 k.Limits.MaxRequestBodySize = 5000,即 KestrelServerOptions.Limits.MaxRequestBodySize,这是所有请求体大小的默认上限;
  • 请求层(按需覆盖):端点内通过 context.Features.Get<IHttpMaxRequestBodySizeFeature>() 取得 IHttpMaxRequestBodySizeFeature,在读取请求体之前把 MaxRequestBodySize 改为 555,实现按请求粒度收紧/放宽上限;
  • IsReadOnly 属性指示该值是否已被下游锁定(一旦开始读取请求体,值即不可再改)。

响应以 HTML 形式同时展示当前值和只读状态。这一 Feature 对"同一应用既传小表单又传大文件"的场景很实用:大文件端点动态调高上限,而不是全局放开。

11. IHttpResponseBodyFeature:统一的响应写出通道

样例:features-http-body-response

README 描述:"This new Feature interface consolidate previous version's three response body APIs into one"(这个较新的 Feature 接口把早期版本的三个响应体 API 合并为一个)。

using Microsoft.AspNetCore.Http.Features;
using System.Text;

var app = WebApplication.Create();
app.Run(async context =>
{
    context.Response.Headers.Append("Content-Type", "text/html; charset=utf-8");
    var feature = context.Features.Get<IHttpResponseBodyFeature>();
    await feature.StartAsync();
    await feature.Stream.WriteAsync(Encoding.UTF8.GetBytes("<html><body style=\"font-size:240px;text-align:center;\">Hello 🌍</body></html>"));
    await feature.CompleteAsync();
});
app.Run();

IHttpResponseBodyFeature 的生命周期是三步式协议:

  1. StartAsync():启动响应写出(内部完成缓冲刷新、内容长度确定等准备工作);
  2. feature.Stream:直接得到底层 Stream,样例向其写入 240px 大字号居中的 Hello 🌍 页面;
  3. CompleteAsync():收尾,标记响应写入完成。

在更底层的场景(自定义中间件写二进制、流式输出、绕过 HttpResponse.Body 封装)中,这条 Start/Stream/Complete 通道提供了比高层 API 更直接的响应体控制。

小结与运行方式

projects/features 目录的 11 个样例覆盖了 Feature 机制的完整使用面:

样例 核心接口 解决的问题
features-server-addresses IServerAddressesFeature 获取应用监听的 URL 列表
features-server-addresses-2 IServer + IServerAddressesFeature 拿不到 IApplicationBuilder 时在中间件中读地址
features-server-request IHttpRequestFeature 直接读取/修改底层请求对象
features-connection IHttpConnectionFeature 本地/远程 IP、端口、连接 ID
features-server-custom 自定义 ICustomFeature 定义自定义 Feature 并在中间件间传递
features-server-custom-override 自定义 ICustomFeature 管道中替换 Feature 实现
features-request-culture IRequestCultureFeature 检测请求文化
features-session ISessionFeature 中间件中使用内存 Session
features-session-redis-2 ISessionFeature(Redis 存储) Redis 分布式 Session
features-max-request-body-size IHttpMaxRequestBodySizeFeature 按请求设置请求体大小上限
features-http-body-response IHttpResponseBodyFeature 统一的 Start/Stream/Complete 响应写出

运行前提:仓库根目录 global.json 固定 SDK 为 10.0.0(rollForward: major、允许预发布),各样例 csproj 目标框架为 net10.0;除 Session with Redis 样例需要本机 Redis(localhost:6379)外,其余样例在对应目录下执行 dotnet run 即可直接验证。

登录后查看全文
practical-aspnetcore