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,665 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 28,786 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);
            }
        }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Jerry Fu - MSFT 901 Reputation points Microsoft Vendor
    2024-11-25T07:36:25.82+00:00

    Hi @Dondon510,

    You could retrieve values from HttpContext like following:

    public async Task awsUploadAsync()
    {
        var form = await HttpContext.Request.ReadFormAsync();
        // Retrieve form fields
        var hostName = form["hostName"].ToString();
        var accessCode = form["accessCode"].ToString();
        var tifFile = form.Files["tifFile"];
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".  Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

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.