Search code examples
c#file-uploadasp.net-core-webapiiformfile

Asp.Net Core API File Upload


I am trying to create a log file upload API for an application (ASP.NET Core 3.1/C#). Basically, a file should be able to be uploaded on demand to the URL, and it save to Azure BLOB storage for later viewing.

When Testing from Postman, I have mixed results. If I leave the Content-Type header as-is, I get a "415 Unsupported Media Type" error:

Postman Unsupported Media Type error

enter image description here

If I un-check the Content-Type header, I hit the API successfully, but the log file is always NULL. After reading numerous posts with similar issues, I've tried with and without [FromForm], [Consumes], and a host of other such small changes, but cannot figure it out.

I'm assuming there's something simple I'm doing wrong or missing, but I'm out of ideas!

Below is the code for my API endpoint

        [HttpPost]
        [Consumes("multipart/form-data")]
        [Route("/api/beam/v1/{orgCode}/device/{deviceCode}/log")]
        [Authorize]
        public async Task<IActionResult> PostLogAsync(string orgCode, string deviceCode, [FromForm(Name = "log")] IFormFile log)
        {
            string lvBlobFileName;
            string lvContainerName;

            string strContent = Request.ContentType;

            lvContainerName = _configuration["StorageContainerLogs"];

            BlobContainerClient container = GetCloudBlobContainer(lvContainerName);

            lvBlobFileName = $"{orgCode}/{deviceCode}/{deviceCode}_{DateTime.Now.ToString("yyyyMMddhhmmss")}";
            BlobClient blob = container.GetBlobClient(lvBlobFileName);

            if (log == null)
                return Ok("No files to upload");

            using (Stream reader = log.OpenReadStream())
            {
                await blob.UploadAsync(reader);
            }

            return Ok();
        }

Any help appreciated!


Solution

  • As far as I know, if you want to post the file which will be auto model bind to the iformfile, you should use form-data instead of binary.

    More details, you could refer to below postman setting:

    enter image description here

    Result:

    enter image description here