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

React+Axios传FormData与ID至C#时遇ArgumentNullException问题

问题原因分析

报错的核心原因是前端手动设置了multipart/form-data请求头,但未包含必要的boundary分隔符。Axios在发送FormData时会自动生成包含boundary的Content-Type(格式类似multipart/form-data; boundary=----WebKitFormBoundaryXXXX),手动覆盖后会丢失boundary,导致后端MultipartFormDataParser无法正确解析请求流,抛出ArgumentNullException。

另外需确认前端传递的messageId是有效的Guid字符串,避免后端[FromHeader]绑定参数时出现异常。

解决方案

1. 前端修改:移除手动设置的Content-Type

修改Axios请求配置,删除手动指定的"Content-Type": "multipart/form-data",让Axios自动处理请求头:

hubConnection.invoke("SendMessage", toUser?.UserId, textMessage, repliedMessage?.id ?? null )
    .then((messageId) => {
        console.log("Message ID:", messageId);
       
        selectedFiles.forEach((file, index) => {
            formData.append(`file${index}`, file);
        });           
        if (selectedFiles && messageId) {
            axios.post(`http://localhost:8220/api/Chat/UploadFile`, formData, {
                headers: {
                    "Authorization": `Bearer ${token}`,
                    "Message-Id": messageId // 保留Header传递messageId
                }
            }).then((response) => {
            }).catch((error) => {
            });
        }
    }).catch((error) => {
        console.error("Mesaj gönderirken hata oluştu", error);
    });

2. 后端优化(可选)

添加参数验证并确保请求流处于起始位置,避免因流位置异常导致解析失败:

[HttpPost("UploadFile")]
[SwaggerResponse(200, "return", typeof(OkResult))]
[SwaggerOperation(Summary = "Upload File", Description = "Upload File for Chat")]
public async Task<IActionResult> UploadFile([FromHeader, Required] Guid messageId)
{
    // 重置请求流到起始位置
    Request.Body.Position = 0;
    await _chatBusiness.UploadFile(Request.Body, messageId);
    return Ok();
}

3. 业务逻辑层保持原有代码

只要请求流格式正确,原解析代码无需修改即可正常运行:

public async Task UploadFile(Stream incoming, Guid messageId)
{
    var parser = MultipartFormDataParser.Parse(incoming, Encoding.UTF8);
    if (parser.Parameters.Count == 0 && parser.Files.Count == 0) 
        throw new Exception("Stream Error");
    // 后续业务逻辑处理...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:46:22