You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写RESTful客户端接收Results.File并实现文件转发代理?

实现文件下载转发的代理客户端

核心思路

用HttpClient先从你的/myapi接口获取文件流,再将该流直接转发到目标WebAPI服务器,全程尽量避免将文件写入本地磁盘,提升效率。


1. 控制台版代理客户端(主动触发转发)

以下是完整的C#代码实现:

using System.Net.Http;
using System.Net.Http.Headers;

class Program
{
    // 复用HttpClient,避免频繁创建销毁
    private static readonly HttpClient _httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        try
        {
            // 1. 从你的API下载文件
            var downloadUrl = "http://localhost:5000/myapi"; // 替换为你的API实际地址
            using var downloadResponse = await _httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead);
            downloadResponse.EnsureSuccessStatusCode(); // 确保下载请求成功

            // 获取原文件的Content-Type,默认设为image/jpeg
            var contentType = downloadResponse.Content.Headers.ContentType?.MediaType ?? "image/jpeg";

            // 2. 将文件流转发到目标WebAPI服务器
            var targetApiUrl = "http://target-server.com/upload"; // 替换为目标API实际地址
            using var streamContent = new StreamContent(await downloadResponse.Content.ReadAsStreamAsync());
            streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            using var uploadResponse = await _httpClient.PostAsync(targetApiUrl, streamContent);
            uploadResponse.EnsureSuccessStatusCode();

            Console.WriteLine("文件转发完成");
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求出错: {ex.Message}");
        }
    }
}

2. ASP.NET Core版代理API(被动转发请求)

如果需要做一个中间代理服务,接收外部请求后自动下载并转发,可以这样实现:

// 在Program.cs中添加代理端点
app.MapGet("/proxy", async (HttpClient httpClient) =>
{
    try
    {
        // 1. 从你的API下载文件
        var downloadUrl = "http://localhost:5000/myapi";
        using var downloadResponse = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead);
        downloadResponse.EnsureSuccessStatusCode();

        var contentType = downloadResponse.Content.Headers.ContentType?.MediaType ?? "image/jpeg";
        var contentStream = await downloadResponse.Content.ReadAsStreamAsync();

        // 2. 转发到目标API
        var targetApiUrl = "http://target-server.com/upload";
        using var streamContent = new StreamContent(contentStream);
        streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);

        using var uploadResponse = await httpClient.PostAsync(targetApiUrl, streamContent);
        uploadResponse.EnsureSuccessStatusCode();

        return Results.Ok("文件转发成功");
    }
    catch (HttpRequestException ex)
    {
        return Results.BadRequest($"转发失败: {ex.Message}");
    }
});

关键注意点

  • 务必复用HttpClient,不要在每次请求时新建,否则会耗尽系统套接字资源
  • 使用HttpCompletionOption.ResponseHeadersRead可以在获取响应头后就开始读取流,不用等待整个响应下载完成,提升响应速度
  • 保留原文件的Content-Type,确保目标API能正确识别文件类型
  • 异常处理重点捕获HttpRequestException,判断请求链路中是否出现错误

内容的提问来源于stack exchange,提问作者s k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:45:14