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

末鹿安然 提交于 2019-12-10 18:38:00

问题


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:

This call is never finishing as the Kestrel is failing

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


回答1:


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);
}



回答2:


I tried and it worked. Maybe you forget to do something. Remove [FromBody] attribute.

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

Postman automatically attaches the correct Content-Type, select form-data option in body section and add your file with file key.

It should work.




回答3:


Seems like there is an error problem with Postman macOS application. When I'm using the postman chrome extension everything works as expected.

MacOS app

Chrome extension




回答4:


I know this has been answered, but you seem to having decided for an workaround. There is nothing wrong with your endpoint nor with the Postman request, I had the same issue and installing the native Postman for my OS solved the problem https://www.getpostman.com/apps



来源:https://stackoverflow.com/questions/51424273/net-core-2-1-post-an-iformfile-using-postman-the-application-completed-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!