Search code examples
c#post.net-coreasp.net-core-2.0iformfile

.net core 2.1 "POST" an IFormFile using Postman - the application completed without reading the entire request body


I'm working on a dotnet core WebAPI 2.1 and I can't find a way of sending to into the Body an image.

The controller looks like this:

    [HttpPost("api/image")]
    public IActionResult Post([FromBody]IFormFile file)
    {
        var filePath = Path.GetTempFileName();
        if (file.Length > 0)
        {
            return Ok();
        }
        return BadRequest();
    }

And this is my Postman call: enter image description here

This call is never finishing as the Kestrel is failing enter image description here

I've already tried to use Consumes

[Consumes("application/json", "application/json-patch+json", "multipart/from-data")]

Also in postman, I have set Content-Type to multipart/form-data


Solution

  • Try doing it like this. Use the same request in postman you are using now. This is just crude boilerplate method but you get the idea.

    Also, dont forget to set headers of your request in postman to: Content-Type: multipart/form-data

    [HttpPost]
    [Route("api/image")]
    public async Task<IHttpActionResult> InsertNewMerchant()
    {
            // your form data is here
                 var formData = HttpContext.Current.Request.Form;
                 HttpFileCollection files = HttpContext.Current.Request.Files;
    
    
                if (files.Count == 1)
                {
                // this is the file you need 
                    var image = files[0];
                        // do something with the file
                }
        return StatusCode(System.Net.HttpStatusCode.Created);
    }