3

I created Web API endpoint to receive a zip file which looks like this

    [HttpPut()]
    [Consumes("application/zip")]
    public async Task<IActionResult> ImportZip()
    {
        var zipFile = HttpContext.Request.Form.Files.FirstOrDefault();
        ....

And I'm trying to test it via Postman with such request: enter image description here enter image description here

But I'm getting exception "System.InvalidOperationException: Incorrect Content-Type: application/zip"

What I'm doing wrong? Thanks!

EDIT Request actually passes through [Consumes("application/zip")] attribute, but crashing on "HttpContext.Request.Form.Files.FirstOrDefault();"

EDIT2 Ok, so finally I successfully received a file when I didn't put any header in the request and removed [Consumes("application/zip")] attribute. In Request.Form.Files my file have a type "application/x-zip-compressed" but when I'm trying to use it in headers content-type and in Consumes attribute I get same crash System.InvalidOperationException: Incorrect Content-Type: application/x-zip-compressed

Roman Borovets
  • 818
  • 12
  • 25

2 Answers2

2

Postman will send multipart/form-data as Content-Type. Normaly you only specify the Consumes attribute when the web api action has to support multiple content types or when you wan't to support a specific content type.

As your web api action depends on HttpContext.Request.Form.Files the Content-Type has to be multipart/form-data anyway.

The best option to only allow zip files is to try parsing it. If it fails you know a wrong file has been uploaded.

[HttpPut("api/import")]
public IActionResult ImportZip()
{
    var file = Request.Form.Files.FirstOrDefault();
    if (file == null)
        return BadRequest();

    try
    {
        using (var zip = new ZipArchive(file.OpenReadStream()))
        {
            // do stuff with the zip file
        }
    }
    catch
    {
        return BadRequest();
    }

    return Ok();
}

Another option would be to check the BOM (Byte order mark) of the file.

NtFreX
  • 10,379
  • 2
  • 43
  • 63
1

You can use IFormFile to transfer your zip. Your WebApi endpoint must be updated to this:

 [HttpPut]
 [Consumes("multipart/form-data")]
 public void Put(IFormFile file)
 {
    var stream = file.OpenReadStream();
 }

Postman request should look something like this (You don't need Content-Type header as it gets resolved on request):

enter image description here

Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
  • 1
    Thanks, @Oluwafemi! It's working actually, and with this approach I can read a file from request like I did before (`HttpContext.Request.Form.Files.FirstOrDefault();`). But as I understand - all files in request will be read and I want to have restriction only for zip – Roman Borovets Oct 02 '17 at 09:42