在ASP.NET Core 2.2中,Request.Form.Files
属性用于访问HTTP请求中的文件上传部分。如果你遇到了 System.InvalidOperationException
异常,并且错误信息提示内容类型为 'asp.net-json'
不正确,这通常意味着请求的内容类型不是预期的 multipart/form-data
,而是 application/json
。
Content-Type
头。确保客户端在发送文件上传请求时,设置了正确的 Content-Type
为 multipart/form-data
。
// 使用Fetch API发送文件上传请求
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('/upload', {
method: 'POST',
body: formData
});
确保服务器端代码正确处理 multipart/form-data
类型的请求。
[HttpPost("upload")]
public async Task<IActionResult> UploadFile()
{
if (Request.Form.Files.Count > 0)
{
var file = Request.Form.Files[0];
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
if (!Directory.Exists(uploads))
{
Directory.CreateDirectory(uploads);
}
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
return Ok(new { message = "File uploaded successfully." });
}
else
{
return BadRequest("No file uploaded.");
}
}
在控制器方法中添加对 Content-Type
的验证。
[HttpPost("upload")]
public async Task<IActionResult> UploadFile()
{
if (Request.ContentType != "multipart/form-data")
{
return BadRequest("Content-Type must be multipart/form-data");
}
// 处理文件上传的逻辑...
}
通过上述步骤,你应该能够解决 System.InvalidOperationException
异常,并确保你的ASP.NET Core应用程序正确处理文件上传请求。
领取专属 10元无门槛券
手把手带您无忧上云