2.6HTTP 声明式请求(代理方式)
HTTP 声明式请求机制通过实现 IHttpDeclarative 接口,在程序运行时动态地构建实现类。该机制会智能地拦截符合特定规则的方法调用,并自动生成相应的 HTTP 远程请求代码。这种方法不仅极大地减轻了开发人员编写 HTTP 请求代码的负担,而且使得代码结构更加条理分明,更易于进行组织、维护和复用。
HTTP 声明式请求机制通过实现 IHttpDeclarative 接口,在程序运行时动态地构建实现类。该机制会智能地拦截符合特定规则的方法调用,并自动生成相应的 HTTP 远程请求代码。这种方法不仅极大地减轻了开发人员编写 HTTP 请求代码的负担,而且使得代码结构更加条理分明,更易于进行组织、维护和复用。
以下示例简单展示了如何定义和使用 HTTP 声明式请求:
1. 定义接口 IHttpService 并实现 IHttpDeclarative
public interface IHttpService : IHttpDeclarative{ // 获取网站内容 [Get("https://furion.net")] Task<string> GetWebSiteContent(); // 携带请求数据 [Post("https://localhost:7044/HttpRemote/AddModel")] [QueryParam("query1", 1)] // 设置查询参数 Task<YourRemoteModel> PostData([QueryParam(AliasAs = "query2")] string param, [Body(MediaTypeNames.Application.Json)] object data); // 设置查询参数并指定别名和请求内容 // Form 表单提交 [Post("https://localhost:7044/HttpRemote/AddForm?id=1")] Task<YourRemoteFormResult> PostForm(Action<HttpMultipartFormDataBuilder> multipart); // Form 表单提交 [Post("https://localhost:7044/HttpRemote/AddForm?id=1")] Task<YourRemoteFormResult> PostForm2([Multipart(AsFormItem = false)] object obj, [Multipart("file", AsFileFrom = FileSourceType.Path)] string filePath); // URL 编码表单提交 [Post("https://localhost:7044/HttpRemote/AddURLForm")] Task<YourRemoteModel> PostURLForm([Body(MediaTypeNames.Application.FormUrlEncoded)] object data);}2. 注册 IHttpService 服务
在 Startup.cs 或 Program.cs 文件中,注册并配置 HttpRemote 服务以支持 HTTP 声明式请求:
services.AddHttpRemote(builder =>{ // 注册单个 HTTP 声明式请求接口 builder.AddHttpDeclarative<IHttpService>(); // 扫描程序集批量注册 HTTP 声明式请求接口(推荐此方式注册) // builder.AddHttpDeclarativesFromAssemblies([Assembly.GetEntryAssembly()]); // 如果使用的是 Furion 框架,可直接传入 App.Assemblies});3. 注入 IHttpService 服务
在需要使用 IHttpService 的类中,通过依赖注入获取其实例:
public class YourService{ private readonly IHttpService _httpService; public YourService(IHttpService httpService) { _httpService = httpService; }}若您使用的是 .NET 8 及以上版本时,可通过主构造函数注入简化代码:
public class YourService(IHttpService httpService){ // 使用 httpService 变量}或者,您也可以在特定方法中按需注入:
public class YourService{ public Task<string> GetResource([FromServices] IHttpService httpService) { // 您的代码逻辑 }}4. 调用 IHttpService 方法
使用注入的 IHttpService 实例调用其方法,以发送 HTTP 请求并获取响应:
// 获取网站内容var content = await httpService.GetWebSiteContent();// 携带请求数据var content = await httpService.PostData("furion", new { id = 1, name = "furion" });// Form 表单提交var content = await httpService.PostForm(multipart => multipart .AddJson(new { id = 1, name = "furion" }) // 设置常规字段 .AddFileAsStream(@"C:\Workspaces\httptest.jpg", "file"));var content = await httpService.PostForm2(new { id = 1, name = "furion" }, @"C:\Workspaces\httptest.jpg");// URL 编码表单提交var content = await httpService.PostURLForm(new { id = 1, name = "furion" });通过使用 HTTP 声明式请求,您可以显著减少编写 HTTP 请求代码的工作量,并使代码更加简洁、易于组织和维护。在大型项目或多人合作项目中,这种方式尤其推荐。