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

C#中PostAsync请求返回400错误,如何正确传递参数?

问题分析与修复方案

问题根源

  • JSON格式不合法:你手动拼接的JSON没有给键名和数组元素加双引号,不符合标准JSON语法,接口解析时直接报错。
  • Stream不可查找引发的错误:IFormFile.OpenReadStream()返回的是NoWriteNoSeekStream,这类流不支持随机访问,而MultipartFormDataContent处理文件流时需要进行seek操作,所以触发了nowritenoseekstreamcontent提示。
  • 参数传递方式不符合接口预期:你给scanMethods的StringContent指定了application/json媒体类型,把它当成了独立的JSON内容块,但多数文件上传接口期望这类参数是普通表单字段,直接传JSON字符串即可。

修复后的代码

// 用序列化生成标准JSON,避免手动拼接出错
var scanMethods = new { scanMethods = new[] { "ANTIVIRUS" } };
string json = JsonSerializer.Serialize(scanMethods);

var content = new MultipartFormDataContent();

// 将scanMethods作为普通表单字段传递
content.Add(new StringContent(json, Encoding.UTF8), "scanMethods");

// 把IFormFile的流复制到可查找的MemoryStream中
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
memoryStream.Position = 0; // 重置流指针到开头
var fileContent = new StreamContent(memoryStream);
// 可选:设置文件的Content-Type,和原文件保持一致
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);

content.Add(fileContent, "file", file.FileName);

var response = await client.PostAsync(url, content);

额外提示

如果接口明确要求scanMethods是独立的JSON内容部分,可以保留StringContent的application/json类型,但必须保证JSON格式绝对正确,同时处理好流的可查找问题。不过绝大多数文件上传场景下,用普通表单字段传递JSON字符串就能满足要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:55:13