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

.NET Core 6中JSON字符串转IFormFile遇空引用异常求助

.NET Core 6中JSON转FormFile触发NullReferenceException的解决方案

在.NET Core 6中将JSON字符串转换为FormFile时,两种实现代码均触发NullReferenceException,错误提示ContentDisposition和ContentType不能为空。

尝试的代码如下:

var memoryStream = new MemoryStream(Encoding.Default.GetBytes(JsonConvert.SerializeObject(content)));

var formFile = new FormFile(memoryStream, 0, memoryStream.Length, "test", "test.json")
{
   ContentType = "application/json",
   Headers = new HeaderDictionary(),
};

// OR

var memoryStream = new MemoryStream(Encoding.Default.GetBytes(JsonConvert.SerializeObject(content)));
    
var formFile = new FormFile(memoryStream, 0, memoryStream.Length, "test", "test.json");

问题原因

FormFile内部验证逻辑会检查Content-Disposition和ContentType头的有效性,之前的代码要么未添加Content-Disposition头,要么未正确初始化Headers导致相关属性为空,触发空引用异常。

解决方案

需同时正确初始化Headers、设置ContentType,并添加符合HTTP规范的Content-Disposition头,同时确保流位置正确。示例代码:

var jsonStr = JsonConvert.SerializeObject(content);
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
// 将流指针重置到起始位置,避免后续读取无内容
memoryStream.Seek(0, SeekOrigin.Begin);

var formFile = new FormFile(memoryStream, 0, memoryStream.Length, "test", "test.json")
{
    ContentType = "application/json",
    Headers = new HeaderDictionary()
};
// 添加符合规范的Content-Disposition头
formFile.Headers.Add("Content-Disposition", $"form-data; name=\"test\"; filename=\"test.json\"");

关键注意点

  • 使用Encoding.UTF8代替Encoding.Default,避免系统默认编码不一致导致的内容乱码
  • 必须重置MemoryStream的位置到开头,否则读取流时会返回空内容
  • Content-Disposition头格式需严格遵循form-data; name="字段名"; filename="文件名"的规范,这是FormFile验证的必要条件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:35:04