:::: MENU ::::

Upload file from swagger UI in ASP.NET Core Web API

If you want to learn how to add swagger in ASP.Net Core then check my previous post. In this post, I will show you how to customize swagger UI to upload a file in ASP.Net Core Web API project. First, let’s add an action which will be responsible to upload a file in our API. If you want to know more about how to upload a file (from Postman) and save it in Azure storage then check my previous post.

If you run your application and navigate to swagger UI in this action you will see multiple input fields associate with IFormFile class properties. If you are like me then you just want file choose control instead of multiple fields mapped with the properties. In fact, that’s what we need to upload a file.

Now let’s replace this multiple fields with file choose control

Let’s use IOperationFilter provided by swashbuckle to detect this operation so we can replace or override the parameter with our custom file upload control before showing it in Swagger UI.

What this filter will do is If it found any operation with OperationIdapifileuploadpost” (OperationId format is [route up to your action]+[httpverb]) then it will clear all parameters in this case it will clear properties of IFormFile interface which are going to projected as input fields in UI  and add new custom parameter with the appropriate name and parameter type.

While you are adding custom field then Name must be same as parameter name of operation (in my case its  “file”) and In property have to be formData and Type must be file. You can set other properties for this parameter as per your need. At last add new consumes type for that operation i.e “application/form-data” which needs to be included for file transfer.

Now we have created filter operation i.e. FileOperation  which filter the operation/action with operationId and add custom control instead of properties of IFormFile. And the final thing to do is register FileOperaion filter in a swagger configuration section.

Now let’s run this application and test this action.

You can see parameter name is file, type is formData and Data Type is file. Which means this control is mapped to the parameter of your action and ready to upload the file. Now choose file and hit try it out button.

 

That’s it. Here we got file data that we just uploaded. This is how you can upload a file from Swagger UI by customizing parameter type. If you need to save this file on azure then check my previous post. The sample is on GitHub.

Happy Coding 🙂


  • Jackson Savitraz

    This is exactly what I was looking for! Thanks