为什么ASP.NET Core的路由处理器能改用任意Delegate类型函数的?

摘要:毫不夸张地说,路由是ASP.NET Core最为核心的部分。路由的本质就是注册一系列终结点(Endpoint),每个终结点可以视为“路由模式”和“请求处理器”的组合,它们分别用来“选择”和“处理”请求。请求处理器通过RequestDeleg
毫不夸张地说,路由是ASP.NET Core最为核心的部分。路由的本质就是注册一系列终结点(Endpoint),每个终结点可以视为“路由模式”和“请求处理器”的组合,它们分别用来“选择”和“处理”请求。请求处理器通过RequestDelegate来表示,但是当我们在进行路由编程的时候,却可以使用任意类型的Delegate作为处理器器,这一切的背后是如何实现的呢? 一、指定任意类型的委托处理路由请求 二、参数绑定 三、返回值处理 一、指定任意类型的委托处理路由请求路由终结点总是采用一个RequestDelegate委托作为请求处理器,上面介绍的这一系列终结点注册的方法提供的也都是RequestDelegate委托。实际上IEndpointConventionBuilder接口还定义了如下这些用来注册终结点的扩展方法,它们接受任意类型的委托作为处理器。 public static class EndpointRouteBuilderExtensions { public static RouteHandlerBuilder Map(this IEndpointRouteBuilder endpoints, string pattern, Delegate handler); public static RouteHandlerBuilder Map(this IEndpointRouteBuilder endpoints, RoutePattern pattern, Delegate handler); public static RouteHandlerBuilder MapMethods(this IEndpointRouteBuilder endpoints, string pattern, IEnumerable<string> httpMethods, Delegate handler); public static RouteHandlerBuilder MapGet(this IEndpointRouteBuilder endpoints, string pattern, Delegate handler); public static RouteHandlerBuilder MapPost(this IEndpointRouteBuilder endpoints, string pattern, Delegate handler); public static RouteHandlerBuilder MapPut(this IEndpointRouteBuilder endpoints, string pattern, Delegate handler); public static RouteHandlerBuilder MapDelete(this IEndpointRouteBuilder endpoints, string pattern, Delegate handler); }由于表示路由终结点的RouteEndpoint对象总是将RequestDelegate委托作为请求处理器,所以上述这些扩展方法提供的Delegate对象最终还得转换成RequestDelegate类型,两者之间的适配或者类型转换是由如下这个RequestDelegateFactory类型的Create方法完成的。这个方法根据提供的Delegate对象创建一个RequestDelegateResult对象,后者不仅封装了转换生成的RequestDelegate委托,终结点的元数据集合也在其中。RequestDelegateFactoryOptions是为处理器转换提供的配置选项。
阅读全文