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

原生JS客户端向.NET Core API传参时控制器接收值为null如何解决

问题排查与解决方案

核心问题原因

  • 表单提交未阻止默认行为:没有调用e.preventDefault(),原生表单提交会触发页面刷新,异步请求可能未完成就被中断。
  • axios传参语法错误:axios.post标准语法为axios.post(请求地址, 提交数据, 配置项),你额外传入了无效的第二个参数"sendFile",导致实际提交的数据和配置项位置全部错位。
  • 数据格式混用错误:后端接口用[FromForm]接收表单数据,你却将普通字段和文件封装为JSON对象,还错误地把FormData塞到JSON属性中,后端无法识别混合格式的数据。
  • 请求头配置错误:同时设置了两个冲突的Content-Type,且使用FormData时无需手动指定multipart/form-data,手动设置会丢失浏览器自动生成的分隔符boundary,导致后端解析表单失败。
  • 字段名不匹配:文件字段你在FormData里设置的键是fileInput,如果后端ErrorModel中接收文件的属性名为Documents,键名不一致会导致数据绑定失败。

修复方案

前端修正代码

const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", (e) => {
  // 阻止表单默认提交刷新行为
  e.preventDefault();
  debugger;
  var name = document.getElementById("errorInput").value;
  var description = document.getElementById("errorDescriptionInput").value;
  var date = document.getElementById("errorDateInput").value;
  var mail = document.getElementById("senderEmailInput").value;
  var file = document.getElementById('fileInput').files[0];

  // 所有字段都放到FormData中,不要封装成JSON
  var formData = new FormData();
  // 普通字段直接append,键名和后端ErrorModel属性名保持一致
  formData.append('ErrorName', name);
  formData.append('ErrorDescription', description);
  formData.append('ErrorSubmittedDate', date);
  formData.append('SenderEmail', mail);
  // 文件字段键名和后端接收文件的属性名保持一致
  formData.append('Documents', file);

  // 修正axios传参顺序,不要手动设置Content-Type
  axios.post("https://localhost:44310/api/Error/senderror", formData)
  .then(res => console.log('提交成功', res))
  .catch(err => console.error('提交失败', err));
})

后端注意事项

确保ErrorModel类定义和前端提交的字段完全匹配,示例参考:

public class ErrorModel
{
    public string ErrorName { get; set; }
    public string ErrorDescription { get; set; }
    public DateTime ErrorSubmittedDate { get; set; }
    public string SenderEmail { get; set; }
    // 接收文件用IFormFile类型
    public IFormFile Documents { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:36:03