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

转curl下载文件命令为C#代码遇异常:Cannot send a content-body with this verb-type

问题排查:GET请求携带Content导致的异常

原始curl命令

curl --location --request GET "https://xxx.xxxx.xxx/artifacts?session=016e1f70-d9da-41bf-b93d-80e281236c46&path=/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log" -H "Authorization:Bearer xxxx" -H "Accept:application/json" --output C:\Temp\Game.log

错误的C#代码

string SessionId = "016e1f70-d9da-41bf-b93d-80e281236c46";
string Token = "xxxx";
string FilePath = "/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log";

string Endpoint = string.Format("https://xxx.xxxx.xxx/artifacts?session={0}&path={1}", SessionId, FilePath);
HttpRequestMessage HttpRequestMsg = new HttpRequestMessage();
HttpRequestMsg.RequestUri = new Uri(Endpoint);
HttpRequestMsg.Method = HttpMethod.Get;
HttpRequestMsg.Headers.Add("Accept", "application/json");
HttpRequestMsg.Headers.Add("Authorization", string.Format("Bearer {0}", Token));

HttpRequestMsg.Content = new StringContent(string.Format("--output {0}", OutFilePath), Encoding.UTF8, "application/json");

using (HttpClient Client = new HttpClient())
{
    var HttpResponseTask = Client.SendAsync(HttpRequestMsg);
}

异常原因

Cannot send a content-body with this verb-type异常的核心原因:

  • HTTP规范中,GET请求语义用于获取资源,不允许携带请求体(Content)。
  • 错误将curl的--output参数当成请求内容添加到HttpRequestMsg.Content中,实际上--output是curl的本地参数,作用是把服务器返回的响应内容写入本地文件,并非发送给服务器的请求部分。

修正方案

  1. 移除HttpRequestMsg.Content的赋值代码,GET请求不需要请求体。
  2. 发送请求后,读取响应流并写入本地文件,实现curl--output的功能。
  3. 正确处理异步操作,使用await等待请求完成,避免资源泄漏。

修正后的完整代码

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string SessionId = "016e1f70-d9da-41bf-b93d-80e281236c46";
        string Token = "xxxx";
        string FilePath = "/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log";
        string OutFilePath = @"C:\Temp\Game.log";

        string Endpoint = $"https://xxx.xxxx.xxx/artifacts?session={SessionId}&path={FilePath}";
        HttpRequestMessage HttpRequestMsg = new HttpRequestMessage(HttpMethod.Get, Endpoint);
        HttpRequestMsg.Headers.Add("Accept", "application/json");
        HttpRequestMsg.Headers.Add("Authorization", $"Bearer {Token}");

        using (HttpClient Client = new HttpClient())
        {
            using (var HttpResponse = await Client.SendAsync(HttpRequestMsg))
            {
                HttpResponse.EnsureSuccessStatusCode();
                using (var fileStream = new FileStream(OutFilePath, FileMode.Create, FileAccess.Write))
                {
                    await HttpResponse.Content.CopyToAsync(fileStream);
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者0xBADF00

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:50:58