Search code examples
c#asp.net-web-apiasp.net-corepostman

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?


Solution

  • 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!