I tried to send file by JS Fetxh API to ASP .NET 6 WebAPI and get 400 status.
let data = new FormData()
data.append('file', file)
const response = await fetch('https://localhost:7054/Pictures',
{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: data
});
[HttpPost]
public async Task<ActionResult> Index([FromBody]IFormFile file)
{
try
{
using (var fs = new FileStream(dir, FileMode.Create))
{
await file.CopyToAsync(fs);
}
return StatusCode(StatusCodes.Status201Created);
}
catch
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
If delete FormData and send 'file' get the same error. If delete 'Content-Type' get 415 status in every case. If set 'Content-Type' to 'application/json' and IFormFile change to string, then send json it works ok.
catchblock is being triggered and you're getting back an HTTP 500 response, then take note of the fact that yourcatchblock ignores the actual exception. In such a case your first step would be to examine the exception being caught.