39. 远程请求
远程请求统一用 Furion 的 IHttpRemoteService(Startup.cs 里一行 services.AddHttpRemote() 注册),仓库里从「同步行政区划」「解析 IP」「推送企业微信」到「定时 HTTP 作业」「接口压测」全部走它。禁止非法爬虫。
原理与流程
services.AddHttpRemote() Admin.NET.Web.Core/Startup.cs
│
▼
IHttpRemoteService(注入即用)
├─ ① 字符串拓展 "http://a.com".GetAsync() / .PostAsync()
├─ ② 代理接口 interface IXxx : IHttpDispatchProxy + [Get]/[Post]
└─ ③ 构建器 HttpRequestBuilder.Get/Post/Create(...) ← 仓库主力用法
│
├─ .SetHttpClientName("WORK_WEIXIN") → 走 HttpRemote.json 的命名客户端
├─ .SetUserAgent(UserAgents.Chrome.PC)
├─ .SetTimeout(TimeSpan) / .SetJsonContent(json, Encoding)
├─ .WithHeaders(dict) / .WithQueryParameters / .WithPathParameters
├─ .SimulateBrowser(true) → 模拟浏览器头
└─ .StressTestHarness(url) → 压测专用
│
▼
SendAsync(builder) → HttpResponseMessage
SendAsAsync<T>(builder) → 直接反序列化(仓库里配合 Clay.Parse 处理动态 JSON)
GetAsStringAsync(url) / PostAsync(url, builder) / GetAsStreamAsync(url)一、三种用法,仓库里实际用的是第三种
// ① 字符串拓展(Furion 提供,写 demo 最省事)
using var res = await "http://admin.net/get".GetAsync();
using var res2 = await "http://admin.net/post".PostAsync();
// ② 声明式代理接口
public interface IHttp : IHttpDispatchProxy
{
[Get("http://admin.net/get")] Task<Xxx> GetXxxAsync();
[Post("http://admin.net/post")] Task<Xxx> PostXxxAsync();
}
// ③ 构建器(Admin.NET 全仓库采用)
var res = await _httpRemoteService.SendAsAsync<string>(HttpRequestBuilder.Get(apiUrl).SimulateBrowser(true));注册与配置:
// Admin.NET.Web.Core/Startup.cs
services.AddHttpRemote();// Admin.NET.Application/Configuration/HttpRemote.json
{
"HttpProxy": { // 代理配置
"Encrypt": false,
"MaxRetries": 3,
"Address": "http://route.xiongmaodaili.com/xxxxxxxx",
"Account": "",
"Password": ""
},
"HttpRemote": {
"WorkWeixin": { // 命名客户端
"EnabledLog": true,
"UseCookies": false,
"EnabledProxy": false,
"HttpName": "WORK_WEIXIN", // ← SetHttpClientName("WORK_WEIXIN") 对应它
"BaseAddress": "https://qyapi.weixin.qq.com",
"Headers": { "User-Agent": "WORK_WEIXIN" },
"Timeout": 60
}
}
}选项类 Admin.NET.Core/Option/HttpProxyOptions.cs:Encrypt / MaxRetries / Address / Account / Password。
二、GET 取字符串:同步行政区划
// Admin.NET.Core/Service/Region/SysRegionService.cs
private readonly IHttpRemoteService _httpRemoteService;
[DisplayName("同步行政区划(民政部)")]
public async Task SyncRegionMzb(MzbInput input)
{
var html = await _httpRemoteService.GetAsStringAsync("http://xzqh.mca.gov.cn/map");
// 抓页面里的 var json = [...]
var proJson = Regex.Match(html, @"(?<=var json = )(\[\{.*?\}\])(?=;)").Value;
dynamic provList = Clay.Parse(proJson); // 动态解析 JSON
foreach (var proItem in provList)
{
var province = new SysRegion
{
Id = YitIdHelper.NextId(),
Name = Regex.Replace((string)proItem.shengji, "[((].*?[))]", ""),
Code = proItem.quHuaDaiMa,
CityCode = proItem.quhao,
Level = 1,
Pid = 0,
};
// …
}
}Clay.Parse 是 Furion 的动态 JSON 类型,配合 dynamic 可以直接 proItem.xxx 取字段,省去定义 DTO。
三、GET + 反序列化:在线解析 IP
// Admin.NET.Core/Utils/CommonHelper.cs
public static async Task<(string ipLocation, double? longitude, double? latitude)> GetIpInfoFromOnline(string ip)
{
if (IPAddress.TryParse(ip, out _)) return ("未知", 0, 0);
var apiUrl = $"https://api.iping.cc/v1/query?ip={ip}&language=zh";
var res = await App.GetRequiredService<IHttpRemoteService>()
.SendAsAsync<string>(HttpRequestBuilder.Get(apiUrl).SimulateBrowser(true));
dynamic ipInfo = Clay.Parse(res);
if (ipInfo.code != 200) return ("未知", 0, 0);
return ($"{ipInfo.data.country} {ipInfo.data.region} {ipInfo.data.city} {ipInfo.data.isp}",
Convert.ToDouble(ipInfo.data.longitude), Convert.ToDouble(ipInfo.data.latitude));
}天地图地理编码是同一套路(带返回值判空):
// Admin.NET.Core/Service/Common/SysCommonService.cs
public async Task<TiandituGeocoderOutput> GetTiandituCoordinate(string keyWord)
{
if (string.IsNullOrWhiteSpace(keyWord)) return null;
var key = App.GetConfig<string>("Tianditu:Key", true);
var apiUrl = $"http://api.tianditu.gov.cn/geocoder?ds={{\"keyWord\":\"{keyWord}\"}}&tk={key}";
var res = await _httpRemoteService.SendAsAsync<string>(HttpRequestBuilder.Get(apiUrl));
dynamic geocoder = Clay.Parse(res);
if (geocoder.msg != "ok") return null;
return new TiandituGeocoderOutput
{
Lon = geocoder.location.lon<double>(),
Lat = geocoder.location.lat<double>()
};
}四、POST JSON:企业微信机器人
// Admin.NET.Core/Service/Message/SysWeComService.cs
private async Task SendMessage(string key, string content)
{
await _httpRemoteService.PostAsync($"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}",
builder => builder
.SetContent(new StringContent(new
{
msgtype = "markdown",
markdown = new { content }
}.ToJson(), Encoding.UTF8, "application/json")));
}五、完整构建器:HTTP 定时作业
Admin.NET.Core/Service/Job/Http/HttpJob.cs 是最能体现构建器能力的例子——把请求参数完全配置化:
public class HttpJob : IJob
{
private const string INVALID_HTTP_ERROR_MESSAGE = "Invalid HTTP job request. (Parameter 'RequestUri')";
private readonly IHttpRemoteService _httpRemoteService;
private readonly IScheduleLogger _logger;
public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
{
var jobDetail = context.JobDetail;
var httpJobMessage = JSON.Deserialize<HttpJobMessage>(jobDetail.GetProperty<string>(nameof(HttpJob)));
if (httpJobMessage == null || string.IsNullOrWhiteSpace(httpJobMessage.RequestUri))
{
_logger.LogWarning(INVALID_HTTP_ERROR_MESSAGE);
context.Result = INVALID_HTTP_ERROR_MESSAGE;
return;
}
// 创建构建器
var httpRequestBuilder = HttpRequestBuilder.Create(httpJobMessage.HttpMethod, httpJobMessage.RequestUri)
.SetHttpClientName(httpJobMessage.ClientName)
.SetUserAgent(UserAgents.Chrome.PC);
if (httpJobMessage.Timeout != null)
httpRequestBuilder.SetTimeout(TimeSpan.FromMilliseconds(httpJobMessage.Timeout.Value));
// 非 GET/HEAD 且有 Body → application/json
if (httpJobMessage.HttpMethod != HttpMethod.Get && httpJobMessage.HttpMethod != HttpMethod.Head
&& !string.IsNullOrWhiteSpace(httpJobMessage.Body))
httpRequestBuilder.SetJsonContent(httpJobMessage.Body, Encoding.UTF8);
if (httpJobMessage.Headers is { Count: > 0 }) httpRequestBuilder.WithHeaders(httpJobMessage.Headers);
var httpResponseMessage = await _httpRemoteService.SendAsync(httpRequestBuilder, stoppingToken);
if (httpJobMessage.EnsureSuccessStatusCode)
httpResponseMessage = httpResponseMessage!.EnsureSuccessStatusCode();
string responseContent;
if (httpJobMessage.PrintResponseContent)
{
responseContent = await httpResponseMessage!.Content.ReadAsStringAsync(stoppingToken);
_logger.LogInformation($"Received HTTP response body with a length of <{responseContent.Length}> output as follows - {(int)httpResponseMessage.StatusCode}{Environment.NewLine}{responseContent}");
}
else responseContent = "COMPLETED";
context.Result = JSON.Serialize(new { httpResponseMessage!.StatusCode, Body = responseContent });
httpResponseMessage.Dispose();
}
}承载参数的 DTO(HttpJobMessage.cs):
public sealed class HttpJobMessage
{
public string RequestUri { get; set; }
public HttpMethod HttpMethod { get; set; } = HttpMethod.Get;
public Dictionary<string, string> Headers { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public string Body { get; set; }
public string ClientName { get; set; } = nameof(HttpJob);
public bool EnsureSuccessStatusCode { get; set; } = true;
public int? Timeout { get; set; }
public bool PrintResponseContent { get; set; } = true;
[JsonIgnore] public string GroupName { get; set; }
[JsonIgnore] public string Description { get; set; }
}六、压测:StressTestHarness
后台【系统管理】里的性能压测工具就是它(SysCommonService.StressTest):
[DisplayName("性能压力测试")]
public async Task<StressTestHarnessResult> StressTest(StressTestInput input)
{
var stressTestHarnessResult = await _httpRemoteService.SendAsync(
HttpRequestBuilder.StressTestHarness(input.RequestUri)
.SetNumberOfRequests(input.NumberOfRequests) // 并发请求数量
.SetNumberOfRounds(input.NumberOfRounds) // 压测轮次
.SetMaxDegreeOfParallelism(input.MaxDegreeOfParallelism) // 最大并发度
.With(builder => builder
.WithHeaders(input.Headers)
.WithQueryParameters(input.QueryParameters)
.WithPathParameters(input.PathParameters)
.SetJsonContent(input.JsonContent)));
return stressTestHarnessResult;
}七、下载远程流:OSS 预签名地址
// Admin.NET.Core/Service/File/FileProvider/OSSFileProvider.cs
public async Task<FileStreamResult> GetFileStreamResultAsync(SysFile file, string fileName)
{
var filePath = Path.Combine(file.FilePath ?? "", file.Id + file.Suffix);
var httpRemoteService = App.GetRequiredService<IHttpRemoteService>();
// 预签名 5 分钟有效,再拉流
var stream = await httpRemoteService.GetAsStreamAsync(
await _OSSService.PresignedGetObjectAsync(file.BucketName, filePath, 5));
return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName + file.Suffix };
}八、在业务 Service 里自己发起请求
把 IHttpRemoteService 直接注入即可(SysRegionService、SysWeComService、SysCommonService、HttpJob 都是这么做的):
namespace Admin.NET.Application;
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class WeatherService : IDynamicApiController, ITransient
{
private readonly IHttpRemoteService _httpRemoteService;
public WeatherService(IHttpRemoteService httpRemoteService) => _httpRemoteService = httpRemoteService;
/// <summary>
/// 拉取天气(GET + 反序列化)
/// </summary>
[DisplayName("拉取天气")]
public async Task<WeatherOutput> GetWeather(string city)
{
var url = $"https://api.example.com/weather?city={Uri.EscapeDataString(city)}";
var json = await _httpRemoteService.SendAsAsync<string>(
HttpRequestBuilder.Get(url).SetUserAgent(UserAgents.Chrome.PC));
dynamic obj = Clay.Parse(json);
if (obj.code != 0) throw Oops.Oh($"天气接口返回异常:{obj.msg}");
return new WeatherOutput { Temp = obj.data.temp, Desc = obj.data.desc };
}
/// <summary>
/// 推送到第三方(POST + 自定义头 + 超时)
/// </summary>
[DisplayName("推送订单")]
public async Task PushOrder(OrderDto order)
{
await _httpRemoteService.PostAsync("https://partner.example.com/api/order",
builder => builder
.SetJsonContent(order.ToJson(), Encoding.UTF8) // 默认 application/json
.SetTimeout(TimeSpan.FromSeconds(30))
.WithHeaders(new Dictionary<string, string>
{
["X-Api-Key"] = App.GetConfig<string>("Partner:ApiKey", true)
}));
// 需要看状态码时用 SendAsync
using var resp = await _httpRemoteService.SendAsync(
HttpRequestBuilder.Post("https://partner.example.com/api/order")
.SetJsonContent(order.ToJson(), Encoding.UTF8));
resp.EnsureSuccessStatusCode();
}
}九、常用 API 速查
| 类别 | 写法 |
|---|---|
| GET 字符串 | await _httpRemoteService.GetAsStringAsync(url) |
| GET 流 | await _httpRemoteService.GetAsStreamAsync(url) |
| GET 泛型 | await _httpRemoteService.GetAsAsync<T>(url) |
| POST | await _httpRemoteService.PostAsync(url, builder => …) |
| 通用发送 | await _httpRemoteService.SendAsync(HttpRequestBuilder.xxx) |
| 通用发送 + 反序列化 | await _httpRemoteService.SendAsAsync<T>(HttpRequestBuilder.xxx) |
| 命名客户端 | .SetHttpClientName("WORK_WEIXIN") |
| 模拟浏览器 | .SimulateBrowser(true) |
| UA | .SetUserAgent(UserAgents.Chrome.PC) |
| 超时 | .SetTimeout(TimeSpan.FromSeconds(30)) |
| JSON Body | .SetJsonContent(jsonString, Encoding.UTF8) |
| 表单 Body | .SetContent(new FormUrlEncodedContent(dict)) |
| 自定义 Content | .SetContent(new StringContent(str, Encoding.UTF8, "application/json")) |
| 请求头 | .WithHeaders(dict) / .WithQueryParameters(...) / .WithPathParameters(...) |
| 路径模板 | "http://a.com/{id}".SetTemplates(new { id = 1 }) |
| 重试 | "http://a.com".SetRetryPolicy(5, 1000).GetAsync() |
| GZip | "http://a.com".WithGZip().GetAsync() |
| HTTP 版本 | "http://a.com".SetHttpVersion("2.0").GetAsync() |
| 下载文件 | await "http://a.com/logo.png".GetToSaveAsync("D:/1.png") |
| 文件上传 | await "http://a.com/upload".SetContentType("multipart/form-data").SetFiles(("key", bytes, "fileName")).PostAsync() |
| 拦截请求 | .OnRequesting((client, req) => { … }) |
| 拦截响应 | .OnResponsing((client, res) => { … }) |
| 拦截异常 | .OnException((client, res, errors) => { … }) |
| 静态方式 | await HttpRequestPart.Default().SetRequestUrl(url).GetAsStringAsync() |
| 取 Cookies | var cookies = response.GetCookies(); |
字符串拓展方式的完整清单(await "http://admin.net/..." 链式):
await "http://admin.net/post".SetHttpMethod(HttpMethod.Get);
await "http://admin.net/post/{id}?name={name}".SetTemplates(new { id = 1, name = "Admin.NET" });
await "http://admin.net/post".SetHeaders(new { Authorization = "Bearer 你的token" });
await "http://admin.net/get".SetQueries(new { id = 1, name = "Admin.NET" });
await "http://admin.net".SetClient(() => new HttpClient());
await "http://admin.net/api/user/add".SetBody(new { Id = 1, Name = "Admin.NET" }, "application/json");
await "http://admin.net/post".SetContentType("application/json");
await "http://admin.net/post".SetContentEncoding(Encoding.UTF8);
await "http://admin.net/post".SetJsonSerialization<NewtonsoftJsonSerializerProvider>(new JsonSerializerSettings { });
await "http://admin.net/post".SetValidationState(includeNull: true); // 支持 [Required] 模型验证⚠️ Content-Type 设为 application/x-www-form-urlencoded 时,框架底层自动做 UrlEncode,不要自己再编码一次。
十、操作步骤清单
- 确认
Startup.cs有services.AddHttpRemote()(仓库默认已有)。 - 在 Service 构造函数注入
IHttpRemoteService。 - 简单 GET 用
GetAsStringAsync;需要结构化结果用SendAsAsync<string>+Clay.Parse。 - POST 用
PostAsync(url, builder => builder.SetJsonContent(...));要读状态码改用SendAsync+EnsureSuccessStatusCode()。 - 有固定 BaseAddress / 统一 Header 的第三方,去
HttpRemote.json加一个命名客户端,代码里SetHttpClientName引用。 - 周期性调用第三方接口,优先用【系统管理】→【定时任务】里的 HTTP 作业(
HttpJob),把 URL/Method/Body/Headers 配在作业属性里,不用写代码。 - 上线前用【性能压力测试】接口(
StressTest)打一轮,确认对方能扛住。
⚠️ 注意事项与常见坑
- 别自己
new HttpClient():会造成 socket 耗尽,统一走IHttpRemoteService。(仓库里唯一new HttpClient()的地方是SysSmsService.CustomSendSmsTemplate,属于历史遗留。) SendAsync返回的响应要释放:HttpJob里显式调了httpResponseMessage.Dispose(),忘了会泄漏连接。EnsureSuccessStatusCode抛异常:HttpJobMessage.EnsureSuccessStatusCode默认true,第三方返回 4xx/5xx 会让作业失败,调试期可关掉。- 路径模板区分大小写:
SetTemplates(new { id = 1 })的键必须与 URL 里的{id}完全一致。 Clay.Parse是动态的:字段写错不会编译报错,只在运行时取到null,接第三方接口时先打日志确认字段路径(ipInfo.data.city这种多层访问尤其容易错)。- 超时要显式设:不设就用
HttpRemote.json里命名客户端的Timeout(秒),走默认客户端则是HttpClient的 100 秒,第三方慢接口很容易拖垮线程池。 - 代理配置只在需要时开:
HttpProxy.Enabled与命名客户端的EnabledProxy是两层开关,都开了才生效;代理地址写错会导致所有请求超时。 - URL 里的中文要转义:
Uri.EscapeDataString(天地图示例里用的是直接拼接,遇到中文地址会失败,自己写时记得转义)。 - 压测别打生产:
StressTest会真的按NumberOfRequests × NumberOfRounds发请求,先在测试环境验证参数量级。 - 禁止非法爬虫:
SysRegionService抓民政部页面属于公开数据同步,批量抓取第三方站点前务必确认对方robots.txt与授权。
小结
远程请求在 Admin.NET 里只有一个入口 IHttpRemoteService。日常三板斧:GetAsStringAsync 取文本、SendAsAsync<string> + Clay.Parse 取动态对象、PostAsync(url, builder) 提交 JSON;配置化的固定第三方走 HttpRemote.json 的命名客户端;周期性调用直接用定时任务里的 HTTP 作业;上线前用 StressTest 压一轮。