【问题标题】:send data from client (vanilla js) to .net core API将数据从客户端(vanilla js)发送到 .net 核心 API
【发布时间】:2021-11-04 10:48:19
【问题描述】:

vanilla javascript 客户端(我尝试使用 axios/ajax/fetch)

const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", (e) => {
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];

var formData = new FormData();
formData.append('fileInput', file);

const error = {
    ErrorName: name,
    ErrorDescription: description,
    ErrorSubmittedDate: date,
    SenderEmail: mail,
    Documents: formData,
}

axios.post("https://localhost:44310/api/Error/senderror","sendFile", error, {
    "Content-Type": "multipart/form-data",
    "Content-Type": "application/json",
})
})

.net 控制器 API

[EnableCors("policy")]
[HttpPost]
[Route("senderror")]
public async Task<IActionResult> HandleError([FromForm]ErrorModel error)
{
   return Ok();
}

浏览器调试器显示模型包含值,但到达控制器的数据为空。 感谢大家的帮助!

【问题讨论】:

  • 我认为问题出在内容类型上,您不能拥有具有“multipart/form-data”或“application/json”两个值的相同属性。您应该尝试删除“Content-Type”:“application/json”。

标签: javascript c# .net api axios


【解决方案1】:

您正在错误对象内的 formdata 和您已应用的 api 上发送文件

[FromForm]

所以服务器期望表单中的数据,并且您正在发送包含表单数据的对象。我认为如果您将所有数据附加到 formdata 中,那么它会起作用,因为您的 api 期望 formdata 中的数据。像这样更改它

const myForm = document.getElementById("myForm");
myForm.addEventListener("submit", (e) => {
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];

var formData = new FormData();
error.append('ErrorName', name);
error.append('ErrorDescription', description);
error.append('ErrorSubmittedDate', date);
error.append('SenderEmail', file);
error.append('Documents', mail);


axios.post("https://localhost:44310/api/Error/senderror","sendFile", error, {
    "Content-Type": "multipart/form-data",
})
})

你必须设置

"Content-Type": "multipart/form-data",

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 2015-04-06
  • 2020-07-27
  • 1970-01-01
相关资源
最近更新 更多