Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad Request (400) when posting IFormFile

I have a .NET Core API project that has a simple endpoint to upload a file:

[Route("api/[controller]")]
[ApiController]
public class FilesController : Controller
{
    private IFilesService _filesService { get; set; }

    public FilesController(IFilesService filesService)
    {
        _filesService = filesService;
    }

    [HttpPost]
    public async Task<IActionResult> UploadFile(IFormFile file)
    {
        var model = await _filesService.UploadFile(file);
        return Ok();
    }
}

I've tried to test this using Postman, but each time I post a file to the endpoint, I get a 400 Bad Request error. My endpoint never gets hit.

I have several other POST endpoints that work just fine, so it's an issue either with this specific endpoint or with Postman. Here is my setup in Postman:

enter image description here

I've been spinning my wheels trying to figure out what the issue is, but there's not much to this at all, and I'm following examples I've seen online.

What am I doing wrong?

like image 489
Steven Avatar asked Oct 27 '25 03:10

Steven


2 Answers

I see you have set the [ApiController] attribute so I'm assuming that you are running ASP.Net Core 2.1.

If it's not set already, try modifying services.AddMvc() to services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); in Startup.cs.

I had a similar issue a while back and the above change fixed it for me. I found the answer to my problem here.

Hope this helps!

like image 180
Chris.ZA Avatar answered Oct 29 '25 19:10

Chris.ZA


try this.

[HttpPost]
    public async Task<IActionResult> UploadFile([FromForm]IFormFile file)
    {
        var model = await _filesService.UploadFile(file);
        return Ok();
    }

And remove ApiController attribute

like image 20
Khushali Avatar answered Oct 29 '25 19:10

Khushali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!