How to create an API controller that will handles multipart/data

Dondon510 221 Reputation points
2024-11-23T08:36:20.2266667+00:00

Hello,

I use ASP NETCore 6, How to create an API controller that will handles multipart/data with the following keys:

tifFile --> File

hostName --> string

accessCode --> string

I tried the following using postman, it goes there but I don't have an idea on how to extract the key and its value?

[HttpPost]
[Route("/api/AWS/Upload")]
[AllowAnonymous]
public async Task awsUploadAsync() 
{
    // how to get the tifFile, hostName, and accessCode value here
}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,645 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 28,621 Reputation points
    2024-11-23T22:30:03.15+00:00

    The official documentation covers uploading files and posting form inputs.

    https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-9.0

    First, define a model that matches the fields you wish to upload.

        public class UploadModel
        {
            public IFormFile? TifFile { get; set; }
            public string HostName { get; set; } = string.Empty;
            public string AccessCode { get; set; } = string.Empty;
        }
    

    Add the model type in the action signature. Finally, add the [FromForm] attribute to let the action know it should expect a content type of multipart/form-data.

        [Route("api/[controller]")]
        [ApiController]
        public class FileUploadController : ControllerBase
        {
            [HttpPost]
            public IActionResult awsUploadAsync([FromForm] UploadModel model)
            {
                return Ok(model);
            }
        }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.