【发布时间】:2020-02-08 19:33:36
【问题描述】:
我似乎无法找出我的控制器接收空数据的原因。我能够到达控制器,但没有数据传输。当我使用 Postman 使用 Body 和正确的键/数据内容测试 API 时,控制器端一切正常。
我的控制器方法:
[Route("home/api/files")]
public class FileController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Post([FromForm] FileModel file)
{
if (file == null)
return BadRequest("Given data is null");
if (string.IsNullOrEmpty(file.Name))
return BadRequest("File name is undefined");
if (string.IsNullOrEmpty(file.FolderPath))
return BadRequest("FolderPath is undefined");
if (file.File.Length < 0)
return BadRequest("File content is empty");
...
}
}
文件模型:
public class FileModel
{
public string Name { get; set; }
public string Extension { get; set; }
public string FolderPath { get; set; }
public IFormFile File { get; set; }
}
以及客户端 Axios 调用:
export function uploadFile(folderPath, data) {
console.log("upLoadFile", folderPath, data);
const formData = new FormData();
formData.set('name', data.file);
formData.set('extension', data.extension);
formData.set('folderPath', folderPath);
formData.append('file', data);
return axios.post(
"api/files",
formData,
{ headers: { 'Content-Type': 'multipart/form-data}' }})
//{ headers: { 'Content-Type': 'multipart/form-data; boundary=${form._boundary}' }})
.then((response) => {
console.log(response.data);
console.log(response.status);
})
.catch((error) => {
console.log(error);
});
}
我认为问题出在我发送的数据类型上?特别是对于FileModels File 属性类型IFormFile。欢迎所有想法!
使用的Axios 0.19.2版本
【问题讨论】:
-
您是否尝试将
[FromForm]替换为[FromBody]? -
with
[FromBody]我收到来自控制器的回复:415 Unsupported Media Type。与 Postman 和 Axios 的回复相同。 -
尝试将您的
content-type更改为application/json,基于stackoverflow.com/a/46278263/6797509 -
嗯,我试过这个:
{ headers: { 'Content-Type': 'application/json' }},但没有影响。我仍在到达控制器,但file所有属性都是null -
嗯,使用
[FromBody]并将content-type设置为application/json,然后通过postman尝试以row发送数据。请注意将数据类型设置为JSON (application/type)--> i.stack.imgur.com/RdwPZ.png
标签: javascript c# axios asp.net-core-2.0