PAYATHON 2026

如何动态创建 AppModule 任意子类并处理 Kestrel 请求返回值

数据小陈

结论

可以做到,但别把 MapGet 当成运行期的自动发现器。Kestrel 只负责 HTTP 服务器,URL 路由和参数绑定是 ASP.NET Core Endpoint Routing 和 MVC 的事。可行的做法是在启动时扫描 AppModule 子类和 [GetUrl] 特性,为每个 URL 注册一个 endpoint,再在 RequestDelegate 里完成实例创建、初始化、参数绑定、方法调用和返回值转换。返回值转换放在这个统一的 handler 里最省事;如果一定要走 MVC 自动路由,那就用 IResultFilter 或自定义 IActionResultExecutor 把它拦下来。

为什么不能直接让 MapGet 自动处理

MapGet 面向的是写死的类型和方法。你的场景里,类型、方法、初始化方式和返回值转换都要到运行时才知道,这些得靠一套自己的元数据注册器。AddScoped<MyAppModule>() 只能解析写死的类型,没法根据反射结果创建任意子类。

推荐实现步骤

  1. 定义 GetUrlAttribute 和初始化接口。
  2. 启动时扫描程序集,找出所有非抽象 AppModule 子类,以及它们带 GetUrlAttribute 的方法。
  3. 每个方法调用一次 MapMethods,注册对应的路由。
  4. 在 handler 里创建 DI scope,用 ActivatorUtilities.CreateInstance 创建模块,再调用初始化方法。
  5. 从 route、query 和 body 绑定参数,然后反射调用方法。
  6. 按返回类型统一写出响应。

代码示例

[AttributeUsage(AttributeTargets.Method)]
public sealed class GetUrlAttribute : Attribute
{
    public string Url { get; }
    public GetUrlAttribute(string url) => Url = url;
}

public abstract class AppModule
{
    public virtual Task InitializeAsync(HttpContext context) => Task.CompletedTask;
}

public sealed class MyModule : AppModule
{
    [GetUrl("/hello")]
    public string SayHello(string person = "unknown") => $"Hello {person}";
}

注册动态 endpoint:

public static class AppModuleEndpointExtensions
{
    public static void MapAppModules(this IEndpointRouteBuilder app, Assembly assembly)
    {
        foreach (var type in assembly.GetTypes()
            .Where(t => !t.IsAbstract && typeof(AppModule).IsAssignableFrom(t)))
        {
            foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
            {
                var attr = method.GetCustomAttribute<GetUrlAttribute>();
                if (attr is null) continue;

                app.MapMethods(attr.Url, new[] { HttpMethods.Get }, async context =>
                {
                    await using var scope = context.RequestServices.CreateAsyncScope();
                    var module = (AppModule)ActivatorUtilities.CreateInstance(scope.ServiceProvider, type);
                    await module.InitializeAsync(context);
                    var result = await InvokeAndBindAsync(module, method, context);
                    await WriteResultAsync(context, result);
                });
            }
        }
    }
}

参数绑定和调用(简化版,复杂模型需扩展):

static async Task<object?> InvokeAndBindAsync(AppModule module, MethodInfo method, HttpContext context)
{
    var args = method.GetParameters().Select(p =>
    {
        var raw = context.Request.Query[p.Name!].FirstOrDefault()
                  ?? context.Request.RouteValues[p.Name!]?.ToString();
        if (raw is null) return p.HasDefaultValue ? p.DefaultValue : null;
        var target = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType;
        return Convert.ChangeType(raw, target);
    }).ToArray();

    var task = (Task?)method.Invoke(module, args);
    if (task is null) return null;
    await task;
    return task.GetType().GetProperty(nameof(Task<object>.Result))?.GetValue(task);
}

统一返回转换:

static async Task WriteResultAsync(HttpContext context, object? result)
{
    switch (result)
    {
        case null:
            await context.Response.WriteAsync(RenderTemplate());
            break;
        case Stream stream:
            await stream.CopyToAsync(context.Response.Body);
            break;
        case string text:
            await context.Response.WriteAsync(text);
            break;
        case Form form:
            await context.Response.WriteAsync(RenderForm(form));
            break;
        default:
            await context.Response.WriteAsJsonAsync(result);
            break;
    }
}

示例里的 Form 记得换成你库里实际的类型。void 分支得先把原始返回类型记下来,否则分不清它是 void 还是真的返回了 null。

如果使用 MVC 自动路由

MVC 的 action 返回 void 时,最终通常落成 EmptyResult,光看结果分不清“原本是 void、需要模板渲染”和“本来就是空结果”。所以更稳妥的办法是自定义 action 元数据,或者干脆别让 MVC 自动调用,直接用上面的 endpoint 方案。非用 MVC 不可的话,可以在 IResultFilter.OnResultExecuting 里根据 ActionDescriptor 和 context.Result 做转换,也可以自己实现 IActionResultExecutor。但返回值类型信息得存进 action 描述符,否则转换规则会缺一块。

注意事项

  • 路由 URL 先缓存起来,注册前检查冲突,别重复注册。
  • 参数绑定要顾及 POST body、数组、复杂对象、默认值,以及类型转换失败的情况。
  • scoped 服务用 CreateAsyncScope 管起来,避免跨请求泄漏。
  • 初始化方法可能会用到 HttpContext,并发和线程安全要自己留意。
  • 返回 Stream 时设置 Content-Type,并处理客户端中途断开。
  • 反射扫描的结果在启动时缓存好,别每个请求都扫一遍。
  • 插件加载程序集时,依赖隔离和异常处理都要考虑。

备注:内容仅供参考。