Swagger with multipart/formdata .NET Core 6

Introduction:

  What is swagger?

    It is an opensource tool to create, update, and share OpenAPI definitions with clients. Basically, a developer will use this tool to do API documentation.

   In this blog I will explain how to work with multipart/form-data using swagger in .NET Core 6.

Create .NET Core 6 Web API Application:

Step 1: Open Visual studio and select create a new project

ASP.NET Core Web API

Step 2:Click on ASP.NET Core Web API template and select .NET 6 as a framework.

Step 3: Create a model folder and add a below file

Photo.cs

   public class Photo
    {
        public IFormFile formFile { get; set; }
    }

Step 4: Right click on controller folder and add below controller

PhotosController.cs

 public class PhotosController : ControllerBase
    {
        [HttpPost]
        public async Task<ActionResult> PostAsync([FromForm] Photo photo)
        {
            var fileName = photo.formFile.FileName;
            return Ok();
        }
    }

Swagger with multipart/formdata

With ASP.NET Core Web API the swagger API has been already configured in Program.cs file

Swagger configuration

Step 5: Run the application

Swagger page will be loaded in the browser, select photos post resource and click on Try it Out

Swagger

Click on Choose file and upload the image. Click on execute, it will send an image information to the API.

.NET Core FromForm data

As expected we got a Image details in the action.

Note: We should use [FromForm] to make the multipart/form-data request from swagger.

gowthamk91

Leave a Reply

%d bloggers like this: