JNPF 远程请求代理 远程请求代理一、核心功能远程请求代理是 JNPF 框架提供的 HTTP 请求封装系统支持通过接口定义远程 API 调用无需手动编写 HTTP 请求代码。1.1 核心价值接口化定义通过接口定义远程 API自动生成 HTTP 请求代码依赖注入支持通过 DI 容器注入远程服务接口拦截器支持支持请求和响应拦截器实现统一的请求处理重试机制支持请求重试提高系统可靠性配置灵活支持多种配置方式满足不同场景需求二、实现原理2.1 接口定义通过定义接口和特性标记远程 API[Client(https://api.example.com)]publicinterfaceIUserApi{[Get(/users/{id})]TaskUserInfoGetUserInfo(stringid);[Post(/users)]TaskUserInfoCreateUser([Body]UserInfouser);[Put(/users/{id})]TaskUserInfoUpdateUser(stringid,[Body]UserInfouser);[Delete(/users/{id})]TaskDeleteUser(stringid);}2.2 动态代理框架使用DispatchProxy动态生成接口实现publicclassHttpDispatchProxy:DispatchProxy,IHttpDispatchProxy{publicIEventPublisherEventPublisher{get;set;}protectedoverrideobjectInvoke(MethodInfotargetMethod,object[]args){// 解析接口方法和参数varhttpMethodtargetMethod.GetCustomAttributeHttpMethodBaseAttribute();varpathhttpMethod.Path;varbodyargs.FirstOrDefault(aa?.GetType().GetCustomAttributeBodyAttribute()!null);// 构建 HTTP 请求varrequestnewHttpRequestMessage(httpMethod.HttpMethod,path);request.ContentnewJsonContent(body);// 发送请求varresponse_httpClient.SendAsync(request).Result;// 解析响应returnresponse.Content.ReadFromJsonAsync(targetMethod.ReturnType.GenericTypeArguments[0]).Result;}}2.3 请求构建框架自动构建 HTTP 请求┌─────────────────────────────────────────────────────────────┐ │ 请求构建流程 │ ├─────────────────────────────────────────────────────────────┤ │ 1. 解析接口方法 │ │ └── 获取 HTTP 方法和路径 │ ├─────────────────────────────────────────────────────────────┤ │ 2. 解析参数 │ │ ├── 路由参数{id} │ │ ├── 查询参数QueryString │ │ ├── 请求体参数Body │ │ └── 请求头参数Headers │ ├─────────────────────────────────────────────────────────────┤ │ 3. 构建 HttpRequestMessage │ │ └── 设置 HTTP 方法、URL、内容、头信息 │ ├─────────────────────────────────────────────────────────────┤ │ 4. 发送请求 │ │ └── 使用 HttpClient 发送请求 │ ├─────────────────────────────────────────────────────────────┤ │ 5. 解析响应 │ │ └── 将响应内容反序列化为返回类型 │ └─────────────────────────────────────────────────────────────┘三、使用示例3.1 定义远程 API 接口[Client(https://api.example.com)]publicinterfaceIUserApi{[Get(/users)]TaskListUserInfoGetUserList([QueryString]intpageIndex1,[QueryString]intpageSize10);[Get(/users/{id})]TaskUserInfoGetUserInfo(stringid);[Post(/users)]TaskUserInfoCreateUser([Body]UserInfoInputuser);[Put(/users/{id})]TaskUserInfoUpdateUser(stringid,[Body]UserInfoInputuser);[Delete(/users/{id})]TaskDeleteUser(stringid);[Get(/users/search)]TaskListUserInfoSearchUsers([QueryString]stringkeyword);}3.2 注册远程服务在Startup.cs中注册services.AddRemoteRequest();services.AddHttpClientIUserApi();3.3 注入并使用publicclassUserService{privatereadonlyIUserApi_userApi;publicUserService(IUserApiuserApi){_userApiuserApi;}publicasyncTaskUserInfoGetUserInfo(stringuserId){returnawait_userApi.GetUserInfo(userId);}publicasyncTaskUserInfoCreateUser(UserInfoInputuser){returnawait_userApi.CreateUser(user);}}四、特性说明4.1 HTTP 方法特性特性HTTP 方法说明[Get]GET获取资源[Post]POST创建资源[Put]PUT更新资源[Delete]DELETE删除资源[Patch]PATCH部分更新资源[Head]HEAD获取资源头信息4.2 参数特性特性说明[Body]请求体参数序列化为 JSON[QueryString]查询字符串参数[Headers]请求头参数[FormField]表单字段参数4.3 类级别特性特性说明[Client]指定基础地址[Headers]指定默认请求头[Interceptor]指定拦截器类型五、配置选项5.1 客户端配置在appsettings.json中配置{RemoteRequestSettings:{Clients:{IUserApi:{BaseAddress:https://api.example.com,Timeout:00:01:00,Headers:{Accept:application/json,Authorization:Bearer token}}}}}5.2 客户端配置项配置项默认值说明BaseAddressnull基础地址Timeout00:01:00请求超时时间Headers{}默认请求头RetryCount0重试次数RetryTimeout00:00:01重试间隔5.3 服务注册配置services.AddRemoteRequest(options{options.TimeoutTimeSpan.FromSeconds(30);options.RetryCount3;options.RetryTimeoutTimeSpan.FromSeconds(5);});六、高级特性6.1 拦截器实现IHttpInterceptor接口自定义拦截器publicclassAuthInterceptor:IHttpInterceptor{publicTaskOnRequestAsync(HttpRequestMessagerequest){// 在请求发送前添加认证头request.Headers.AuthorizationnewAuthenticationHeaderValue(Bearer,token);returnTask.CompletedTask;}publicTaskOnResponseAsync(HttpResponseMessageresponse){// 在响应返回后处理if(!response.IsSuccessStatusCode){thrownewException(请求失败);}returnTask.CompletedTask;}}注册拦截器[Interceptor(typeof(AuthInterceptor))][Client(https://api.example.com)]publicinterfaceIUserApi{}6.2 重试机制使用[RetryPolicy]特性配置重试策略[RetryPolicy(Count3,Timeout5000)][Client(https://api.example.com)]publicinterfaceIUserApi{}6.3 异步请求接口方法默认异步执行publicinterfaceIUserApi{[Get(/users/{id})]TaskUserInfoGetUserInfo(stringid);}6.4 同步请求也支持同步请求publicinterfaceIUserApi{[Get(/users/{id})]UserInfoGetUserInfo(stringid);}6.5 文件上传支持文件上传publicinterfaceIFileApi{[Post(/upload)]TaskUploadResultUploadFile([FormField]stringfileName,[FormField]HttpFilefile);}6.6 批量请求支持批量请求publicinterfaceIBatchApi{[Post(/batch)]TaskListBatchResultBatchRequest([Body]ListBatchItemitems);}6.7 请求日志框架自动记录请求日志services.AddRemoteRequest(options{options.LogEnabledtrue;});七、核心文件文件说明HttpDispatchProxy.csHTTP 动态代理实现IHttpDispatchProxy.csHTTP 动态代理接口Http.csHTTP 请求入口类HttpRequestPart.csHTTP 请求部分HttpRequestPartMethods.csHTTP 请求方法HttpRequestPartSetters.csHTTP 请求设置器HttpResponseModel.csHTTP 响应模型RemoteRequestServiceCollectionExtensions.cs远程请求服务扩展方法GetAttribute.csGET 请求特性PostAttribute.csPOST 请求特性PutAttribute.csPUT 请求特性DeleteAttribute.csDELETE 请求特性BodyAttribute.cs请求体参数特性QueryStringAttribute.cs查询字符串参数特性ClientAttribute.cs客户端特性InterceptorAttribute.cs拦截器特性RetryPolicyAttribute.cs重试策略特性八、总结远程请求代理通过接口化定义和动态代理技术实现了简洁的远程 API 调用方式。核心设计思想接口化定义通过接口定义远程 API自动生成 HTTP 请求代码动态代理使用DispatchProxy动态生成接口实现无需手动编写请求代码依赖注入支持通过 DI 容器注入远程服务接口拦截器支持支持请求和响应拦截器实现统一的请求处理重试机制支持请求重试提高系统可靠性这种设计使得远程 API 调用更加简洁和便捷提高了开发效率和代码可维护性。

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/10/1 19:32:24
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/30 21:32:07
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/10/2 15:29:32
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/10/1 19:32:23
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/1 19:32:35
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/30 21:32:11

日新闻

周新闻

月新闻