17/01/2021 by Nitesh

Solution: Upload files and JSON in ASP.NET Core Web API

In our previous post, we read about HTTP Verb 405 error in ASP.Net Core. Today, we will know about uploading File and JSON data together on a Web API in ASP.Net Core.

The general definition of a Web API POST call looks like below –

[HttpPost]
public async Task<IActionResult> PostCompany(Company company)
{
      APIResponse response = new APIResponse();
      //Do Operations
      return Ok(response);
}

In case, you are trying to upload a file, the Controller definition looks like below

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
       APIResponse response = new APIResponse();
       //Process File
       return Ok(response);
}

So, you may wonder that if you want to pass both file and object together, you can create the definition as below

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, Company comp)
{
       APIResponse response = new APIResponse();
       //Process File & Do Operations
       return Ok(response);
}

and when you make the call using your favorite tool like Postman, you may get 2 type of errors –

  1. Unsupported Media Type
  2. Model Validation errors (for Company class in our example above)

This is because when you pass both parameters, .Net Core runtime is unable to parse the request data as JSON only and hence the error.

To resolve this error, you need to make small tweak in controller definition as below

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, [FromForm]string jsonData)
{
      Company company = JsonConvert.DeserializeObject<Company>(jsonData);
       APIResponse response = new APIResponse();
       //Process File & Do Operations
       return Ok(response);
}

In the block above, you may notice that we are accepting the JSON object as a string and then deserializing in the function definition block.

You can also pass a List as List<IFormFile> in case you want to send multiple files.

Hope this helps!

Let me know in comments any other approach to solve this problem.

#.Net Core#ASP.Net Core#Web API